Search code examples
arraysdictionarymergejqelement

How do I get the length of elements of each json file in directory containing several jsons


I have a directory with only json files each having a minimum of atleast 1 element

foo.json
bar.json
baz.json

I want to create a new json array with above json files which I am able to with following:

ls | jq -R '{name: split("\\n") | .[]}' | jq -s '.'

which results as:

[
  {
    "name": "foo.json"
  },
  {
    "name": "bar.json"
  },
  {
    "name": "baz.json"
  }
]

But what I need is length of the corresponding elements respective to each of the json file along with the name as below:

[
  {
    "name": "foo.json",
    "size": 5
  },
  {
    "name": "bar.json",
    "size": 10
  },
  {
    "name": "baz.json",
    "size": 15
  }
]

This command gives only size of the json without any mapping to the actual filename

jq -s 'map(length) ' ./*.json

like:

[
  5,
  10,
  15
]
  

Any pointers to have the two commands merged and evolved in better way to get the expected output as mentioned above would be much appreciated

Tried adding size to each element through

ls | jq -R '{name: split("\\n"), size: map(length) | .[]}'

But is resulting in error in iterating


Solution

  • You can use input_filename to get the file name:

    jq -n '[inputs | { name: input_filename, size: length }]' *.json