Home > Enterprise >  Merging one field from a JSON into another JSON using jq
Merging one field from a JSON into another JSON using jq

Time:03-29

I have two JSON files with a similar structure. I want to take one of the item from the first JSON file and add it into the second JSON file using the jq command. I've been trying to do it using map and * without any success.

I have this file:

{
  "items": {
    "foo": {
      "key": "value1"
    },
    "bar": {
      "key": "value2"
    }
  }
}

And this file:

{
  "items": {
    "baz": {
      "key": "value3"
    },
    "qux": {
      "key": "value4"
    }
  }
}

And would like to take the first item on the first file and merge it into the second file, in order to get this output:

{
  "items": {
    "baz": {
      "key": "value3"
    },
    "qux": {
      "key": "value4"
    },
    "foo": {
      "key": "value1"
    }
  }
}

CodePudding user response:

Use to_entries[0] to reduce to the first item, to_entries to reconstruct the object, then update the items object using |=, and use * to merge with the second file accessed through input:

jq '(.items |= ([to_entries[0]] | from_entries)) * input' 1.json 2.json
{
  "items": {
    "foo": {
      "key": "value1"
    },
    "baz": {
      "key": "value3"
    },
    "qux": {
      "key": "value4"
    }
  }
}

Demo

  • Related