In78
In78

Reputation: 462

How to transform a nested objects using jq?

I have a json object of the form:

{
  ...
  objectx: {
    nested_obj1: {
      key1: value1
    },
    nested_obj2: {
      key2: value2
    },
    ...
  },
  ...
}

. I need to add a keyX: valueX to all the nested_objs in objectx using jq.

I was trying to apply a map filter using .objectx | map(.+{keyX: valueX}) but could not figure out how to store this filtered list into the original json object. How can I achieve this?

Upvotes: 1

Views: 421

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134611

Select the objects you wish to update (the values of the objectx object) and set the value you want. map is designed to work on arrays, not objects. map_values can be used for that instead.

.objectx |= map_values(.keyX = $valueX)

Personally I prefer do this:

.objectx[].keyX = $valueX

Note that using [] on an object will yield all values of that object.

Upvotes: 2

Related Questions