How to count items in JSON object using command line?
JsonBashCurlJqJson Problem Overview
I'm getting this kind of JSON
reply from a curl
command:
[ { "cid": 49, "pyn": "yi4", "hans": "亿", "hant": "億", "tid": 68, "l10n": "cent million", "pid": 1, "pos": "num", "pos_txt": "" }, { "cid": 50, "pyn": "yi4", "hans": "亿", "hant": "億", "tid": 69, "l10n": "100 millions", "pid": 1, "pos": "num", "pos_txt": "" }]
How can I count the number of items in the array (here 2
), using Bash
or a command line (e.g. underscore
) ?
Json Solutions
Solution 1 - Json
Just throwing another solution in the mix...
Try jq
, a lightweight and flexible command-line JSON processor:
jq length /tmp/test.json
Prints the length of the array of objects.
Solution 2 - Json
The shortest expression is
curl 'http://…' | jq length
Solution 3 - Json
You can also use jq to track down the array within the returned json and then pipe that in to a second jq
call to get its length. Suppose it was in a property called records
, like {"records":[...]}
.
$ curl https://my-source-of-json.com/list | jq -r '.records | length'
2
$
Solution 4 - Json
If the JSON
is being read from a file, try this -
number_of_objects=`jq '. | length' json_file_name.json`
echo $number_of_objects
If the JSON
array is inside a key in the JSON
as shown below -
{
"fruits": [
"apples",
"oranges",
"pears"
]
}
try this -
number_of_objects=`jq '.fruits | length' json_file_name.json`
echo $number_of_objects
(You'll have to download jq
for this solution to work)
Solution 5 - Json
A simple solution is to install jshon
library :
jshon -l < /tmp/test.json
2
Solution 6 - Json
try qic. it works like jq/jello. qic support interactive mode as well.
cat test.json | qic "len(_)"