Édo*_*pez 157 bash json curl jq
我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": ""
}
]
Run Code Online (Sandbox Code Playgroud)
如何2使用Bash或命令行(例如underscore)计算数组中的项目数(此处)?
Ken*_*Ken 326
只是在混合中抛出另一种解决方案......
尝试jq,一个轻量级和灵活的命令行JSON处理器:
jq length /tmp/test.json
Run Code Online (Sandbox Code Playgroud)
打印对象数组的长度.
yuv*_*lio 24
您还可以使用jq来跟踪返回的 json 中的数组,然后将其通过管道传输到第二次 jq调用中以获取其长度。假设它在一个名为 的属性中records,比如{"records":[...]}。
$ curl https://my-source-of-json.com/list | jq -r '.records | length'
2
$
Run Code Online (Sandbox Code Playgroud)
Dhr*_*wat 22
如果JSON正在从文件中读取,请尝试以下操作 -
number_of_objects=`jq '. | length' json_file_name.json`
echo $number_of_objects
Run Code Online (Sandbox Code Playgroud)
如果JSON数组位于键内,JSON如下所示 -
{
"fruits": [
"apples",
"oranges",
"pears"
]
}
Run Code Online (Sandbox Code Playgroud)
尝试这个 -
number_of_objects=`jq '.fruits | length' json_file_name.json`
echo $number_of_objects
Run Code Online (Sandbox Code Playgroud)
(您必须下载jq此解决方案才能发挥作用)
Kol*_*yon 11
假设这个结构:
(存储在名为 的变量中json)
{
"results": [
{ "id": 1 }
{ "id": 2 }
]
}
Run Code Online (Sandbox Code Playgroud)
如果您想计算 results数组中有多少个,命令是:
$json | jq '.results | length'
Run Code Online (Sandbox Code Playgroud)