Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add json object into another json object using bash/jq

I am trying to create a new file adding the object defined in country1.json into world.json. Essentially:

world.json

{
    "class": "world",
    "version": "1.1.0"
}

+

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

country1.json

{
    "class": "country",
    "country_1": {
        "class": "city",
        "name": "seattle"
    }
}

=

world_country1.json

{
    "class": "world",
    "version": "1.1.0",
    "country1": {
        "class": "country",
        "country_1": {
            "class": "city",
            "name": "seattle"
        }
    }
}

Using the filename for the objects in country1.json file. I would like to use bash/jq if possible.

Thanks for your help,
Best,
Romain

>Solution :

Use input to access the second file, and redirect using > into another file

jq '.country1 = input' world.json country1.json > world_country1.json
{
  "class": "world",
  "version": "1.1.0",
  "country1": {
    "class": "country",
    "country_1": {
      "class": "city",
      "name": "seattle"
    }
  }
}

Demo


If you want to utilize the file’s name for the new field’s name, use input_filename and cut off the last 5 characters (removing .json):

jq '. + (input | {(input_filename[:-5]): .})' world.json country1.json > world_country1.json
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading