How to count items in JSON object using command line?

Édouard Lopez picture Édouard Lopez · Jan 24, 2014 · Viewed 118.6k times · Source

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) ?

Answer

Ken picture Ken · Jan 25, 2014

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.