Join the 2 json report using jq

Viewed 27

I have 2 report files like the following

report1.json

{
  "examples": [
    {
      "description": "desc 1",
      "full_description": "full_description 1",
      "status": "status 1",
      "file_path": "file_path 1",
      "run_time": 0.01
    }
  ]
}

and report2.json

{
  "examples": [
    {
      "description": "desc 2",
      "full_description": "full_description 2",
      "status": "status 2",
      "file_path": "file_path 2",
      "run_time": 0.02
    }
  ]
}

I want to combine it using jq command with hope the end result is as follows

{
  "examples": [
    {
      "description": "desc 1",
      "full_description": "full_description 1",
      "status": "status 1",
      "file_path": "file_path 1",
      "run_time": 0.01
    },
    {
      "description": "desc 2",
      "full_description": "full_description 2",
      "status": "status 2",
      "file_path": "file_path 2",
      "run_time": 0.02
    }
  ]
}

i have tried using this script jq -s '.[0] * .[1]' report1.json report2.json but it doesn't work, is there any solution to be able to combine according to my expected result using jq command ?

3 Answers

Try this:

jq -s ' [ (.[0] | keys[]) as $k | reduce .[] as $item (null; .[$k] += $item[$k]) ] | add' report1.json report2.json

enter image description here

Take the first input (automatically in context), and operarte on all subsequent objects using inputs (without the -n option). Then, simply add up all items you care about:

jq '.examples += [inputs.examples[]]' report*.json 
{
  "examples": [
    {
      "description": "desc 1",
      "full_description": "full_description 1",
      "status": "status 1",
      "file_path": "file_path 1",
      "run_time": 0.01
    },
    {
      "description": "desc 2",
      "full_description": "full_description 2",
      "status": "status 2",
      "file_path": "file_path 2",
      "run_time": 0.02
    }
  ]
}

Demo

If the point of the question is that you don't know the name of the top-level key, then perhaps the following is close to what you want:

jq -n '
 [inputs | to_entries] | add | {(first.key): (map(.value) | add) }
' report{1,2}.json
Related