我有以下JSON结构
{
"a": "aVal",
"x": {
"x1": "x1Val",
"x2": "x2Val"
}
"y": {
"y1": "y1Val"
}
}
Run Code Online (Sandbox Code Playgroud)
我想添加"x3": "x3Val","x4": "x4Val"到x. 所以输出应该是
{
...
"x": {
....
"x3": "x3Val",
"x4": "x4Val",
}
...
}
Run Code Online (Sandbox Code Playgroud)
可以使用jq吗?
当然,这很简单jq:
jq '.x += {"x3": "x3Val","x4": "x4Val"}' file.json
Run Code Online (Sandbox Code Playgroud)
输出:
{
"a": "aVal",
"x": {
"x1": "x1Val",
"x2": "x2Val",
"x3": "x3Val",
"x4": "x4Val"
},
"y": {
"y1": "y1Val"
}
}
Run Code Online (Sandbox Code Playgroud)
是的,只要您在右括号后的第 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"
}
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要将值作为参数传递,请使用选项--arg:
jq --arg v3 "x3val" --arg v4 "x4val" '.x.x3=$v3|.x.x4=$v4' file
Run Code Online (Sandbox Code Playgroud)