如何使用命令行计算 JSON 对象中的项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21334348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 20:12:18  来源:igfitidea点击:

How to count items in JSON object using command line?

jsonbashcurljq

提问by édouard Lopez

I'm getting this kind of JSONreply from a curlcommand:

JSON从一个curl命令得到这样的答复:

[
  {
    "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 Bashor a command line (e.g. underscore) ?

如何2使用Bash或 命令行(例如underscore)计算数组(此处)中的项目数?

回答by Ken

Just throwing another solution in the mix...

只是在混合中加入另一个解决方案......

Try jq, a lightweight and flexible command-line JSON processor:

Try jq,一个轻量级且灵活的命令行 JSON 处理器:

jq length /tmp/test.json

Prints the length of the array of objects.

打印对象数组的长度。

回答by nikolay

The shortest expression is

最短的表达是

curl 'http://…' | jq length

回答by édouard Lopez

A simple solution is to install jshonlibrary :

一个简单的解决方案是安装jshon库:

jshon -l < /tmp/test.json
2