假设有以下 JSON 文件 foo.js(为了简明起见而剥离):
{"a":{"b":[{"x":{"x1":1},"y":{"y1":5}},{"x":{"x1":1},"y":{"y1":6}}]}}
我想用y1的对应值替换x1的值。也就是说,我想得到以下结果:
{"a":{"b":[{"x":{"x1":5},"y":{"y1":5}},{"x":{"x1":6},"y":{"y1":6}}]}}
这会替换数值,但只返回修改后的字典而不是完整的JSON文件:
% jq -Mc '.a.b[] | .x.x1 = .y.y1' foo.js
{"x":{"x1":5},"y":{"y1":5}}
{"x":{"x1":6},"y":{"y1":6}}
以下方法可以将 x1 替换为一个常数值:
% jq -Mc '(.a.b[] | .x.x1) |= 9' foo.js
{"a":{"b":[{"x":{"x1":9},"y":{"y1":5}},{"x":{"x1":9},"y":{"y1":6}}]}}
但是尝试使用相同的想法并不起作用:
% jq -Mc '(.a.b[] | .x.x1) |= .y.y1' foo.js
jq: error (at foo.js:1): Cannot index number with string "y"