0

I have a json structured like this:

[
    { 
      "name": "object1",
      "prop": "prop1",
      "props": [
        { "prop1": "value1" },
        { "prop2": "value2" },
        { "prop3": "value3" }
      ]
    },
    { 
      "name": "object2",
      "prop": "prop2",
      "props": [
        { "prop1": "value4" },
        { "prop2": "value5" },
        { "prop3": "value6" }
      ]
    }
]

I would like to extract the content of the props variable and have it as extra object properties, looking like this:

[
    { 
      "name": "object1",
      "prop": "prop1",
      "prop1": "value1",
      "prop2": "value2",
      "prop3": "value3"
    },
    { 
      "name": "object2",
      "prop": "prop2",
      "prop1": "value4",
      "prop2": "value5",
      "prop3": "value6"
    },
]

I've been trying to use map but I can't seem to be able to get rid of the array.

1 Answer 1

3

Use add to merge the propN objects into one, del to remove the original props:

jq '[.[] | . + (.props | add) | del(.props)]' file.json

You can indeed use map to shorten it a bit:

jq 'map(. + (.props | add) | del(.props))' file.json
Sign up to request clarification or add additional context in comments.

3 Comments

Equivalently jq 'map(. + (.props | add) | del(.props))'
If I wanted to do something else with the rest of the object properties I would need to do it separately, right? jq '{...} | map(...)' file.json.
@FedericoNafria: You can process the result of the map, e.g. map(. + (.props | add) | del(.props)) | .[].name |= ascii_upcase.

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.