Shell 解析 JSON

Shell 下使用 jq 解析 JSON,十分方便。

源数据

$ curl api.dhcp.cn/?json
{
  "IP": "134.175.159.160",
  "Address": {
    "Country": "中国",
    "Province": "广东省",
    "City": "广州市"
  },
  "ISP": "电信"
}

1. 使用 jq 解析 JSON 串

$ curl -s api.dhcp.cn/?json | jq .IP
"134.175.159.160"
  • 获取字典长度

$ curl -s api.dhcp.cn/?json | jq ".Address"
{
  "Country": "中国",
  "Province": "广东省",
  "City": "广州市"
}
$ curl -s api.dhcp.cn/?json | jq ".Address | length"
3
  • 获取嵌套数据

2. Python 解析 JSON 串

reference

Last updated