我正在学习如何使用jq操作json数据,我有一点麻烦。这是我输入的JSON
{
"user":{
"advertisingID":"617a68"
},
"deviceTs":1575387020137,
"activies":[
{
"ts":1575617868326,
"appsUsage":{
"isFull":true,
"data":[
{
"com.orange.phone":44009
}
],
"startTs":1575617281541
}
},
{
"ts":1575618968326,
"appsUsage":{
"isFull":true,
"data":[
{
"uk.green.launcher2":4354
},
{
"com.black.phone":1232
}
],
"startTs":1575617281541
}
}
]
}
我想将所有包含“点”的键替换为“破折号”和预期的输出:
{
"user":{
"advertisingID":"617a68"
},
"deviceTs":1575387020137,
"activies":[
{
"ts":1575617868326,
"appsUsage":{
"isFull":true,
"data":[
{
"com-orange-phone":44009 <----
}
],
"startTs":1575617281541
}
},
{
"ts":1575618968326,
"appsUsage":{
"isFull":true,
"data":[
{
"uk-green-launcher2":4354 <----
},
{
"com-black-phone":1232 <----
}
],
"startTs":1575617281541
}
}
]
}
我尝试过。activies | = map(with_entries(如果.key ==“ appsUsage”然后... else。end))...(split(“。”)| join(“-”))但没有成功,预先感谢。
我认为您不需要正则表达式;我相信split和join内置函数的结合将更有效和干净。
.activies |= walk(
if type == "object" then
reduce (keys_unsorted[] | select(index("."))) as $k (.;
(.[$k | split(".") | join("-")] = .[$k])
| del(.[$k])
)
else . end
)
根据峰的建议,一种更具可读性的解决方案:
.activies |= walk(
if type == "object" then
with_entries(
.key |= gsub("\\.";"-")
)
else . end
)