Federico Nafria
Federico Nafria

Reputation: 1600

JQ convert json array to object properties

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.

Upvotes: 0

Views: 334

Answers (1)

choroba
choroba

Reputation: 241878

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

Upvotes: 3

Related Questions