[英]How to add a field to a JSON object with the jq command?
I have this JSON data: 我有这个JSON数据:
{
"success": true,
"module": {
"data": {
"item_i77f664a2": {
"id": "i77f664a2",
"tag": "item",
"fields": {
"cartItemId": 2012636322
},
"type": "biz"
}
}
}
}
And I want to add {"operation":"delete"}
right below cartItemId
and then save the JSON data to a file. 我想在cartItemId
下面添加{"operation":"delete"}
,然后将JSON数据保存到文件中。 The result that I want is like this: 我想要的结果是这样的:
{
"success": true,
"module": {
"data": {
"item_i77f664a2": {
"id": "i77f664a2",
"tag": "item",
"fields": {
"cartItemId": 2012636322,
"operation": "delete"
},
"type": "biz"
}
}
}
}
This is what I have tried: 这是我尝试过的:
jq '.module.data.item_i77f664a2.fields + {"operation":"delete"}' > data.json
But it doesn't save the JSON data with the output that I want like above. 但它没有使用我想要的输出保存JSON数据。 How do I fix it ? 我如何解决它 ?
This type of update is where the magic of +=
comes into play. 这种类型的更新是+=
的魔力发挥作用的地方。 With your input, the following invocation: 根据您的输入,以下调用:
jq '.module.data.item_i77f664a2.fields += {"operation":"delete"}'
produces the output you indicate you want: 生成您想要的输出:
{
"success": true,
"module": {
"data": {
"item_i77f664a2": {
"id": "i77f664a2",
"tag": "item",
"fields": {
"cartItemId": 2012636322,
"operation": "delete"
},
"type": "biz"
}
}
}
}
However, I am not sure that this will produce what you want in similar circumstances, as you have referenced "item_i77f61ee2". 但是,我不确定这会在类似的情况下产生你想要的东西,因为你引用了“item_i77f61ee2”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.