Given the following JSON file foo.js (stripped down for clarity):
{"a":{"b":[{"x":{"x1":1},"y":{"y1":5}},{"x":{"x1":1},"y":{"y1":6}}]}}
I want to replace the value of x1 with the corresponding value of y1. That is, I want to end up with:
{"a":{"b":[{"x":{"x1":5},"y":{"y1":5}},{"x":{"x1":6},"y":{"y1":6}}]}}
This replaces the values, but returns only the modified dictionaries rather than the complete JSON file:
% jq -Mc '.a.b[] | .x.x1 = .y.y1' foo.js
{"x":{"x1":5},"y":{"y1":5}}
{"x":{"x1":6},"y":{"y1":6}}
This works to replace x1 with a constant value:
% jq -Mc '(.a.b[] | .x.x1) |= 9' foo.js
{"a":{"b":[{"x":{"x1":9},"y":{"y1":5}},{"x":{"x1":9},"y":{"y1":6}}]}}
But this attempt to use the same idea doesn't work:
% jq -Mc '(.a.b[] | .x.x1) |= .y.y1' foo.js
jq: error (at foo.js:1): Cannot index number with string "y"
You almost got it. Use this:
.a.b[] |= (.x.x1 = .y.y1)
We want to update every item in the .a.b array where .x.x1 takes the value of .y.y1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With