Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JQ to replace a value with another value from the same dictionary

Tags:

jq

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"
like image 307
J Greely Avatar asked Jun 27 '26 16:06

J Greely


1 Answers

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

like image 76
Jeff Mercado Avatar answered Jul 04 '26 07:07

Jeff Mercado