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) ?
6 Answers
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.
6The shortest expression is
curl ' | jq length 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 | jq -r '.records | length' 2 $ 2If 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)
A simple solution is to install jshon library :
jshon -l < /tmp/test.json 2 try qic. it works like jq/jello. qic support interactive mode as well.
cat test.json | qic "len(_)"