2

Using jq, how can I take a json object from a file (input_02.json), and append it to output.json, while retaining everything already in output.json (e.g. an object originating from file input_01.json).

The object to be appended in both cases is literally the entire contents of the file, with the file's "id" field as the object's key.

I'm taking a large list of input files (all with the same syntax) and essentially combining them like that.

The command i'm using to create the object to be appended is as follows:

jq '{(.id):(.)} ' input_01.json

which gives me:

{
  "input1_id": {

  }
}

input_1.json:

{
  "id": "input1_id",
  "val": "testVal1"
}

input2.json:

{
  "id": "input2_id",
  "val": "testVal2"
}

desired output:

{
  "input1_id": {
    "id": "input1_id",
    "val": "testVal1"
  },
  "input2_id": {
    "id": "input2_id",
    "val": "testVal2"
  }
}
qmacro
  • 3,025
  • 23
  • 33
John Bergqvist
  • 852
  • 13
  • 38

2 Answers2

1

You’re on the right track with {(.id):(.)}. The following should handle the case you mentioned, and might give you some ideas about similar cases:

program.jq: map({(.id):(.)}) | add

Invocation:

jq -s -f program.jq input_01.json input_02.json
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
peak
  • 105,803
  • 17
  • 152
  • 177
-2

You could use "jf" for this from https://pypi.python.org/pypi/jf

$ pip install jf

$ jf 'chain(), {y["id"]: y for y in x}' input1.json input2.json
{
  "input2_id": {
    "id": "input2_id",
    "val": "testVal2"
  },
  "input1_id": {
    "id": "input1_id",
    "val": "testVal1"
  }
}
Al Hoo
  • 528
  • 5
  • 11