简体   繁体   中英

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:

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 [] :

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

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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