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

Counting Fields in single JSON String

If you want to test individual JSON strings, you can echo these and pipe the output to jq:

echo '{"username":"user1","id":1000}' | jq '. | length'
> 2

Counting JSON Fields from File

If you are working with JSON records in a file you can simply pass the file path as a argument to jq. This will print the number of fields in each JSON record in the file.

jq '. | length' test_file.json

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

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

Leave a Reply

Count the Number of Fields in JSON with jq