How to consolidate JSON records from multiple files using jq

Viewed 77

I have a list of file names as shell variable and their contents like below

file_names=('one.json' 'two.json')

one.json:

{
      "key":"k1",
      "host": "..",
      "name": ".."    
}

two.json:

{
      "key":"k2",
      "host": "..",
      "name": ".."
}

I want to create a consolidate file with all the contents from the above files. There can be more than 2 files. In the consolidate file the key value will become the outer level key of the JSON record. eg:

{
    "k1": {
      "host": "..",
      "name": ".."   
    },
    "k2": {
      "host": "..",
      "name": ".."   
    }
}

How can I achieve this using jq ?

1 Answers

Using INDEX:

jq -n 'INDEX(inputs; .key) | map_values(del(.key))' "${file_names[@]}"
Related