# Shell 解析 JSON

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

源数据

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

### 1. 使用 jq 解析 JSON 串 <a href="#id-1-shi-yong-jq-jie-xi-json-chuan" id="id-1-shi-yong-jq-jie-xi-json-chuan"></a>

```
$ 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
```

* 获取嵌套数据

```
$ curl -s api.dhcp.cn/?json | jq .Address.City
"广州市"
```

### 2. Python 解析 JSON 串 <a href="#id-2python-jie-xi-json-chuan" id="id-2python-jie-xi-json-chuan"></a>

```
$ curl -s 'api.dhcp.cn/?json' | \
  python -c "import sys, json; print json.load(sys.stdin)['IP']"
134.175.159.160
```

### reference <a href="#reference" id="reference"></a>

* \[1] justcode. [Shell：无比强大的shell之json解析工具jq](http://justcode.ikeepstudying.com/2018/02/shell%EF%BC%9A%E6%97%A0%E6%AF%94%E5%BC%BA%E5%A4%A7%E7%9A%84shell%E4%B9%8Bjson%E8%A7%A3%E6%9E%90%E5%B7%A5%E5%85%B7jq-linux%E5%91%BD%E4%BB%A4%E8%A1%8C%E8%A7%A3%E6%9E%90json-jq%E8%A7%A3%E6%9E%90-json/)
* \[2] Tom CzHen. [使用 Shell 脚本来处理 JSON](https://www.tomczhen.com/2017/10/15/parsing-json-with-shell-script/)
