5

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 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice! I was missing the final piece to add the .name field.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.