【问题标题】:jq select() and sort_by()jq select() 和 sort_by()
【发布时间】: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排序。

提前致谢

【问题讨论】:

    标签: json api curl jq


    【解决方案1】:

    jqsort_by() 函数接受一个数组作为输入。

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

    样本输出:

    asdfg   7
    another-test    9
    

    【讨论】:

    • 太棒了! @tsv 有什么用?我怎样才能得到每行一个值? (同一行没有数字和名称)
    • @Bruno9779,欢迎,@tsv 会将值数组转换为以tab 分隔的项目字符串。每个输入数组将打印为一行。您可以仅使用 | .name, .parent_id 打印“每行一个值”(就像您之前所做的那样)
    • 希望我能为@tsv 给@RomanPerekhrest 100 分。通过column -t 将整个命令通过管道传输,以改进终端上的表格输出
    猜你喜欢
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 2016-07-05
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多