Home > OS >  Count the number of key value pairs in a given JSON structure using jq
Count the number of key value pairs in a given JSON structure using jq

Time:10-05

Given a JSON structure that looks similar to this:

{
  "foo": "bar",
  "baz": 5,
  "qux": false
}

How do I find out how many key value pairs are in it? In JavaScript I could call Object.keys(myJson).length to get the result, but it would be much more convenient for me to do it with jq directly.

CodePudding user response:

Just use length directly on the object.

From the manual:

The length of an object is the number of key-value pairs

{"foo":"bar", "baz":5, "qux":false} | length
3

Demo

CodePudding user response:

You can use jq 'keys | length', which will do exactly the same as Object.keys(myJson).length.

CodePudding user response:

If the object is the input to JQ, then simply length:

echo '{"a":4,"b":2}' | jq 'length'
  • Related