输入
{
"apps": [
{
"name": "whatever1",
"id": "ID1"
},
{
"name": "whatever2",
"id": "ID2",
"dep": [
"a.jar"
]
},
{
"name": "whatever3",
"id": "ID3",
"dep": [
"a.jar",
"b.jar"
]
}
]
}
输出
{
"apps": [
{
"name": "whatever1",
"id": "ID1",
"dep": [
"b.jar"
]
},
{
"name": "whatever2",
"id": "ID2",
"dep": [
"a.jar",
"b.jar"
]
},
{
"name": "whatever3",
"id": "ID3",
"dep": [
"a.jar",
"b.jar"
]
}
]
}
在上面的例子中
whatever1
没有dep
,因此请创建一个。whatever2
有dep
且没有b.jar
,因此请添加b.jar
whatever3
有dep
b.jar
而且 # add blindly, whatever3 is not right
cat dep.json | jq '.apps[].dep += ["b.jar"]'
# missed one level and whatever3 is gone.
cat dep.json | jq '.apps | map(select(.dep == null or (.dep | contains(["b.jar"]) | not)))[] | .dep += ["b.jar"]'
未受影响。我的尝试。
{{1}}
答案 0 :(得分:1)
为了清楚起见,让我们定义一个辅助函数来执行核心任务:
# It is assumed that the input is an object
# that either does not have the specified key or
# that it is array-valued
def ensure_has($key; $value):
if has($key) and (.[$key] | index($value)) then .
else .[$key] += [$value]
end ;
现在可以直接完成任务:
.apps |= map(ensure_has("dep"; "b.jar"))
.apps[] |= ensure_has("dep"; "b.jar")
答案 1 :(得分:0)
cat dep.json | jq '.apps[].dep |= (. + ["b.jar"] | unique)'