Locane
Locane

Reputation: 3144

jq display key names and their child element lengths together

I would like to display an arbitrary object's key names and the lengths of their constituent parts. I think that my trouble appears to be with 'length' requiring a filter, which mutes other output.

Given foo.json contains:

{
    "lol": 1, 
    "wtf": [1, 2, 3, 4], 
    "bbq": {
        "omg": "yes", 
        "afk": "always"
    }
}

I can:

cat foo.json |jq 'keys'
[
  "bbq",
  "lol",
  "wtf"
]

And I can:

cat foo.json |jq '.[] |length'
1
4
2

But how do I get both on the same (or I would even accept alternating) line?

"bbq" 2
"lol" 1
"wtf" 4

Upvotes: 1

Views: 613

Answers (1)

peak
peak

Reputation: 116919

Assuming you want each key with its length on the same line, you could go with something like:

jq -r 'keys_unsorted[] as $k | [$k, (.[$k]|length)] | join(" ")' 

If you want the key name to be quoted, use the filter:

keys_unsorted[] as $k | "\"\($k)\" \(.[$k]|length)"

Upvotes: 3

Related Questions