PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 25, 2022

[FIXED] How to merge different objects and arrays in the same json file using jq

 July 25, 2022     arrays, jq, json     No comments   

Issue

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


Solution

.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



Answered By - 0stone0
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing