Adrian Pronk
Adrian Pronk

Reputation: 13926

Find length of each array field within a JSON object using jq

I have a process that generates a JSON object containing some "header" values as scalars and a number of payload values as arrays:

{
  "header 1": 42,
  "header 2": "2020-01-27",
  "payload 1": [
    {
      "foo": 1
    },
    {
      "foo": 2
    }
  ],
  "another payload": [
    10,
    9,
    8,
    7
  ]
}

I have been able to isolate the names of the array fields with the following command:

$ jq '[to_entries | .[] | select(.value | type == "array")] | from_entries | keys_unsorted' results.json
[
  "payload 1",
  "another payload"
]

But I don't know how to use this to get the lengths of the arrays. The output I'm looking for would be something like:

{
  "payload 1": 2,
  "another payload": 4
}

Or anything that lists the keys of fields that are arrays and the length of the arrays.

What is a jq command to list the lengths of all array fields in the top-level object?

Upvotes: 0

Views: 1085

Answers (1)

oguz ismail
oguz ismail

Reputation: 50795

You don't need *_entries functions here.

map_values(arrays | length)

Online demo

Upvotes: 3

Related Questions