How to count items in JSON object using command line?

JsonBashCurlJq

Json 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(_)"

https://walkerever.github.io/qic/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question&#201;douard LopezView Question on Stackoverflow
Solution 1 - JsonKenView Answer on Stackoverflow
Solution 2 - JsonnikolayView Answer on Stackoverflow
Solution 3 - JsonyuvilioView Answer on Stackoverflow
Solution 4 - JsonDhruv SaraswatView Answer on Stackoverflow
Solution 5 - JsonÉdouard LopezView Answer on Stackoverflow
Solution 6 - JsonY WView Answer on Stackoverflow