JQ add properties to nested object in nested array

Viewed 3415

I have the following json:

{
  "first": {
    "second" : "A"
  },
  "array": [
    {
      "name" : "AAA",
      "something": {
        "hola": "hi"
      }
    },
    {
      "name" : "BBB",
      "something": {
        "hola": "hi"
      }
    }
  ]
}

I would like to trasform it adding a property to the something object, using the value from the name property of the parent, like:

I have the following json:

{
  "first": {
    "second" : "A"
  },
  "array": [
    {
      "name" : "AAA",
      "something": {
        "hola": "hi",
        "NEW_PROPERTY": "AAA"
      }
    },
    {
      "name" : "BBB",
      "something": {
        "hola": "hi",
        "NEW_PROPERTY": "BBB"
      }
    }
  ]
}

Which jq expression can do this?

2 Answers

Try this jq script:

<file jq '.array = [ .array[] | .something.NEW_PROPERTY = .name ]'

This is replacing the array by another one that is the same as the original one with one more key NEW_PROPERTY.

You could simply use the filter:

.array |= map(.something.NEW_PROPERTY = .name)

or if map's not your thing (or if you want to save typing one character):

.array[] |= (.something.NEW_PROPERTY = .name)
Related