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
) ?
A simple solution is to install jshon
library :
jshon -l < /tmp/test.json
2
The shortest expression is
curl 'http://…' | 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 https://my-source-of-json.com/list | jq -r '.records' | jq length
2
$
Source: Stackoverflow.com