Home > Net >  Add json object into another json object using bash/jq
Add json object into another json object using bash/jq

Time:06-02

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"
}

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

CodePudding user response:

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
  • Related