1

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).

peak
  • 105,803
  • 17
  • 152
  • 177
Hellfar
  • 393
  • 2
  • 17

1 Answers1

1

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.

Inian
  • 80,270
  • 14
  • 142
  • 161