jq select()和sort_by()

时间:2018-03-09 18:32:11

标签: json api curl jq

我正在解析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) '

但我无法将这两个功能结合起来。

澄清:我需要提取名称和parent_id,按父级别排序,当它不为空时。

提前致谢

1 个答案:

答案 0 :(得分:3)

jq solution:

sort_by() function accepts an array as input.

curl 'http://...' | jq -r 'map(select(.parent_id != null)) 
                           | sort_by(.parent_id)[] | [.name, .parent_id] | @tsv'

Sample output:

asdfg   7
another-test    9