我处于JSON
结构的下方
{
"a": "aVal",
"x": {
"x1": "x1Val",
"x2": "x2Val"
}
"y": {
"y1": "y1Val"
}
}
我想将"x3": "x3Val","x4": "x4Val"
添加到x
。因此输出应为
{
...
"x": {
....
"x3": "x3Val",
"x4": "x4Val",
}
...
}
是否可以使用jq?
答案 0 :(得分:4)
是的,只要您在右括号}
之后的第8行添加一个逗号(否则jq
不会解析您输入的JSON数据):
$ jq '.x.x3="x3val"|.x.x4="x4val"' file
{
"a": "aVal",
"x": {
"x1": "x1Val",
"x2": "x2Val",
"x3": "x3val",
"x4": "x4val"
},
"y": {
"y1": "y1Val"
}
}
或者,如果您需要将值作为参数传递,请使用选项--arg
:
jq --arg v3 "x3val" --arg v4 "x4val" '.x.x3=$v3|.x.x4=$v4' file
答案 1 :(得分:2)
当然, jq
非常简单:
jq '.x += {"x3": "x3Val","x4": "x4Val"}' file.json
输出:
{
"a": "aVal",
"x": {
"x1": "x1Val",
"x2": "x2Val",
"x3": "x3Val",
"x4": "x4Val"
},
"y": {
"y1": "y1Val"
}
}