简体   繁体   中英

Merging JSON files under their own key using jq

Trying to merge an undefined number of JSON files into one, each represented in their own key (using jq ).

Example:

$ cat foo.json
{
  "test1":"Foo"
}
$ cat bar.json
{
  "test2":"Bar"
}
$ jq -s "{`ls | sed -r 's/\.json$/: \./' | tr '\n' ', ' | sed 's/.$//'`}" `ls`
{
  "foo": [
    {
      "test1": "Foo"
    },
    {
      "test2": "Bar"
    }
  ],
  "bar": [
    {
      "test1": "Foo"
    },
    {
      "test2": "Bar"
    }
  ]
}

As I am trying to output:

{
  "foo": {
    "test1": "Foo"
  },
  "bar": {
    "test2": "Bar"
  }
}

For example: foo being the name of the first file and expected to be the key for its content in the final output.

(Also, I feel like this is not really pretty to call ls twice for the same thing, but not sure if there is a way around).

Roughly based on peak's answer use inputs with -n to read the JSON contents in one shot and removing the extension from the filename

jq -n '
  [inputs
   | {(input_filename | gsub(".*/|\\.json$";"")): .}]
   | add' *.json

Also as suggested by the original author, the solution above only removes UNIX-style paths, but not Windows-style paths.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM