Sometimes when working with JSON on the command line, it is helpful to know how many elements exist in a JSON array. Fortunately this is easy to do with jq. jq is a lightweight, easy to use, command line JSON processor.

*More information about jq can be found at https://stedolan.github.io/jq/manual/.

Counting Array Elements in single JSON String

If you want to count array elements in individual JSON strings, you can echo these and pipe the output to jq:

echo '[{"username":"user1"},{"username":"user2"}]' | jq '. | length'
> 2

Counting Array Elements from File

If you are working with JSON records in a file you can simply pass the file path as a argument to jq. If each record in the file is a JSON array, the following will print the number of elements in that array.

jq '. | length' test_file.json

If it is expected that all JSON records contain the same number of elements, you can simply print the first output line:

jq '. | length' test_file.json | head -1

Counting Elements in Nested Arrays

jq also makes it easy to work with arrays nested within your JSON structure. In the below example, we count the number of array elements in the “users” field.

echo '{"users":[{"username":"user1"},{"username":"user2"}]}' | jq '.users | length'

*More information about jq can be found at https://stedolan.github.io/jq/manual/.

Leave a Reply

Count JSON Array Elements with jq