Count JSON Array Elements with jq

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

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:

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.

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

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.

*More information about jq can be found at

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">