【发布时间】:2018-03-09 18:32:11
【问题描述】:
我正在解析来自 gitlab api 的 curl 输出,我需要在我的查询中添加一个 sort_by,然后只选择某些值。
样本输入:
[
{
"id": 10,
"name": "another-test",
"path": "another-test",
"description": "",
"visibility": "private",
"lfs_enabled": true,
"avatar_url": null,
"web_url": "https://mygitlab/groups/another-test",
"request_access_enabled": false,
"full_name": "another-test",
"full_path": "another-test",
"parent_id": 9
},
{
"id": 11,
"name": "asdfg",
"path": "asdfg",
"description": "",
"visibility": "private",
"lfs_enabled": true,
"avatar_url": null,
"web_url": "https://mygitlab/groups/asdfg",
"request_access_enabled": false,
"full_name": "asdfg",
"full_path": "asdfg",
"parent_id": 7
}
我用 jq 解析 JSON 如下:
curl http://..... | jq -r '.[] | select(.parent_id!=null) | .name, .parent_id'
这完全符合预期,但是当我尝试按 parent_id 对结果进行排序时,出现错误:
curl http://..... | jq -r '.[] | select(.parent_id!=null) | .name, .parent_id | sort_by(.parent_id)'
jq: error (at <stdin>:0): Cannot index number with string "parent_id"
我可以使用 sort_by(),用一个点代替 .[]:
curl http://..... | jq '. | sort_by(.parent_id) '
但我不能将这两个功能结合起来。
澄清:我需要提取name和parent_id,当它不为null时,按parent_id排序。
提前致谢
【问题讨论】: