Bytamine
Bytamine

Reputation: 55

Merge 2 JSON objects from 2 files using jq

I have two json files
1.json

{
  "outputs": {
     "item1": {
       "name": "name1",
       "email": "email1"
     }
  }
}

2.json

{
  "outputs": {
     "item2": {
       "name": "name2",
       "email": "email2"
     }
  }
}

I'm trying to merge them using jq

jq -s '{
      "Items" :
      {
            "list" : .[] | .outputs ,
      },
  }' 1.json 2.json

and I get just two Items objects, but I want to have one Items object and all item* merged like this

{
  "Items": {
    "objects": {
      "item1": {
        "name": "name1",
        "email": "email1"
      },
      "item2": {
        "name": "name2",
        "email": "email2"
      }
    }
  }
}

I've tried .[0] * .[1] trick, but I cannot put it into object construction. How can do this with jq?

Upvotes: 1

Views: 56

Answers (1)

pmf
pmf

Reputation: 36088

Try adding the --slurped array:

jq -s '{Items: {objects: map(.outputs) | add}}' 1.json 2.json

Demo

Another approach could be using reduce with inputs and the -n flag:

jq -n 'reduce inputs.outputs as $i ({}; .Items.objects += $i)' 1.json 2.json

Demo

Output:

{
  "Items": {
    "objects": {
      "item1": {
        "name": "name1",
        "email": "email1"
      },
      "item2": {
        "name": "name2",
        "email": "email2"
      }
    }
  }
}

Upvotes: 2

Related Questions