这篇文章上次修改于 902 天前,可能其部分内容已经发生变化,如有疑问可询问作者。

tmp.json:

{
    "ip": "127.0.0.1",
    "containers": [{
            "container_name": "xremote_server_pc_003",
            "signaling_port": 51111,
            "relay_port": 51112
        },
        {
            "container_name": "xremote_server_pc_005",
            "signaling_port": 51121,
            "relay_port": 51122
        }
    ]
}

1 获得某个字段值

获得 Ip 字段:

ip=$(jq ".ip" conf.json)
echo "ip: $ip"

结果:

ip: "127.0.0.1"

2 解析数组

解析 containers 数组:

containers=$(jq ".containers" conf.json)
for row in $(echo "${containers}" | jq -r ".[] | @base64")
do
    _jq() {
        echo ${row} | base64 --decode | jq -r ${1}
    }

    echo "container_name: $(_jq ".container_name")"
    echo "signaling_port: $(_jq ".signaling_port")"
    echo "relay_port: $(_jq ".relay_port")"
done

结果:

container_name: xremote_server_pc_003
signaling_port: 51111
relay_port: 51112
container_name: xremote_server_pc_005
signaling_port: 51121
relay_port: 51122