문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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 | length'
2
$ 

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)

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

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top