Home > front end >  How to merge different objects and arrays in the same json file using jq
How to merge different objects and arrays in the same json file using jq

Time:07-06

I have a json file with the following contents

 {
    "Cities":
      {
        "city": New York,
        "zip_code": "10034",
        "state": "NY"
      },
    "addresss": [
      {
        "address_line1": 123 Main Street,
        "address_line2": Unit 130
      },
      {
        "address_line1": 5th Avenue,
        "address_line2": East River Tower
      }
    ]
  }

I am trying to combine the two objects ( Cities and array addresss) and create a new array mailing_address as shown below

mailing_address:[
{
        "address_line1": 123 Main Street,
        "address_line2": Unit 130,
        "city": New York,
        "zip_code": "10034",
        "state": "NY"

},
{
        "address_line1": 5th Avenue,
        "address_line2": East River Tower,
        "city": New York,
        "zip_code": "10034",
        "state": "NY"
}
]

I have tried add, map and reduce however all of these approach adds cities only to the first element and not to every element. Is there a way to perform this using jq?

Thank you

CodePudding user response:

.Cities as $c | { mailing_address: (.addresss | map(. * $c)) }

Will output:

{
  "mailing_address": [
    {
      "address_line1": "123 Main Street",
      "address_line2": "Unit 130",
      "city": "New York",
      "zip_code": "10034",
      "state": "NY"
    },
    {
      "address_line1": "5th Avenue",
      "address_line2": "East River Tower",
      "city": "New York",
      "zip_code": "10034",
      "state": "NY"
    }
  ]
}

First we save the Cities object to a variable. Then we create a new object, with your mailing_address key, loop over each address and add (*) the Cities variable to it

Try it online

  • Related