简体   繁体   English

如何用 jq 对 json 列表进行排序

[英]how can you sort json list with jq

I have the following list:我有以下列表:

{
    "list": [
        {
            "ipv4": [
                "192.168.64.193"
            ],
            "name": "node2",
            "release": "20.04 LTS",
            "state": "Running"
        },
        {
            "ipv4": [
                "192.168.64.192"
            ],
            "name": "node1",
            "release": "20.04 LTS",
            "state": "Running"
        }
    ]
}

jq -r '.list[] | [ .name, .ipv4[0] ] | @tsv' file.json

node2   192.168.64.193
node1   192.168.64.192

How can I sort the list?如何对列表进行排序?

I am trying to sort by.name:我正在尝试按.name 排序:

jq -r 'sort_by(.name) | .list[] | [ .name, .ipv4[0] ] | @tsv' file.json
Cannot index array with string "name"

jq -r 'sort_by(.list[].name) | .list[] | [ .name, .ipv4[0] ] | @tsv' file.json
Cannot index array with string "name"

Insert sort_by(.name) after traversing to .list but before iterating over its items with [] :在遍历到.list之后插入sort_by(.name) ,但在使用[]迭代其项目之前:

jq -r '.list | sort_by(.name)[] | [.name, .ipv4[0]] | @tsv' file.json
node1   192.168.64.192
node2   192.168.64.193

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM