此处填充了subThings数组
$ echo '[{"thing-1" : "meta1","thing-2" : "meta2","thing-n" : "metan","subThings":[{"subThing-1" : "subMeta1","subThing-2" : "subMeta2","subThing-n" : "subMetan"}]}]' | jq '.'
[
{
"subThings": [
{
"subThing-n": "subMetan",
"subThing-2": "subMeta2",
"subThing-1": "subMeta1"
}
],
"thing-n": "metan",
"thing-2": "meta2",
"thing-1": "meta1"
}
]
您可以在此处看到丢失的键只是设置为null。
$ echo '[{"thing-1" : "meta1","thing-2" : "meta2","thing-n" : "metan","subThings":[{"subThing-1" : "subMeta1","subThing-2" : "subMeta2","subThing-n" : "subMetan"}]}]' |
jq '[.[] | {"thing-1","thing-5","subThing-2":.subThings[]["subThing-2"],}]'
[
{
"subThing-2": "subMeta2",
"thing-5": null,
"thing-1": "meta1"
}
]
此处数组subThings为空
$ echo '[{"thing-1" : "meta1","thing-2" : "meta2","thing-n" : "metan","subThings":[]}]' | jq '.'
[
{
"subThings": [],
"thing-n": "metan",
"thing-2": "meta2",
"thing-1": "meta1"
}
]
而不是subThing-2的null,它将清除所有数据。
$ echo '[{"thing-1" : "meta1","thing-2" : "meta2","thing-n" : "metan","subThings":[]}]' |
jq '[.[] | {"thing-1","thing-5","subThing-2":.subThings[]["subThing-2"],}]'
[]
$
为什么?
是否有其他方法可以获取数据,而无需空数组清除所有内容?
答案 0 :(得分:0)
您正在尝试根据subThings
对象的存在来生成对象。实际上,这就是.subThings[]
在{"thing-1","thing-5","subThing-2":.subThings[]["subThing-2"]}
的上下文中所做的。
您需要分别评估subThings
并在没有null
的情况下替换为empty
,否则将只是map({ "thing-1", "thing-5", "subThing-2": (.subThings[]."subThing-2" // null) })
而不会产生任何结果(这就是您在此处看到的内容) )。
{{1}}
答案 1 :(得分:-1)
我仍然不知道我得到的json是否错误,或者这是否是jq中的错误。我发现此解决方案使用sed来使数组不为空。
$ echo '[{"thing-1" : "meta1","thing-2" : "meta2","thing-n" : "metan","subThings":[]}]' | sed 's/\[ *\]/[null]/g' | jq '[.[] | {"thing-1","thing-5","subThing-2":.subThings[]["subThing-2"],}]'
[
{
"thing-1": "meta1",
"thing-5": null,
"subThing-2": null
}
]
$