Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65910229/find-length-of-each-array-field-within-a-json-object-using-jq

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need *_entries functions here.

map_values(arrays | length)

Online demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...