仅使用 Bash 解析 JSON

1 bash json cut sed

我有一个 JSON 文件:

{
    "request_id": "9a081c0c-9401-7eca-f55d-50e3b7c0301c",
    "lease_id": "",
    "renewable": false,
    "lease_duration": 2764800,
    "data": {
        "password": "test123",
        "username": "testuser1"
    },
    "wrap_info": null,
    "warnings": null,
    "auth": null
}
Run Code Online (Sandbox Code Playgroud)

我想读的价值usernamepassword。现在我能够集成 bash 和 python 来获得我想要的。

# curl --silent -k https://1.2.3.4:8200/v1/secret/service/clustered -H "X-Vault-Token: c2e3b6ec17df" | python3 -c "import sys, json; print(json.load(sys.stdin)['data']['password'])"
test123

# curl --silent -k https://1.2.3.4:8200/v1/secret/service/clustered -H "X-Vault-Token: c2e3b6ec17df" | python3 -c "import sys, json; print(json.load(sys.stdin)['data']['username'])"
testuser1
Run Code Online (Sandbox Code Playgroud)

但由于我只想使用 bash,我也做了以下工作:

# curl --silent -k https://1.2.3.4:8200/v1/secret/service/clustered -H "X-Vault-Token: c2e3b6ec17df" | sed -n -e 's/^.*password":"//p' | cut -d'"' -f1
test123

# curl --silent -k https://1.2.3.4:8200/v1/secret/service/clustered -H "X-Vault-Token: c2e3b6ec17df" | sed -n -e 's/^.*username":"//p' | cut -d'"' -f1
testuser
Run Code Online (Sandbox Code Playgroud)

我只关心我是否利用了sedcut在这种情况下,正确的命令。或者有没有更好的方法来提取所需的字段?

gru*_*dic 9

我建议使用jq

$ jq '.data.password' data.json
"test123"
Run Code Online (Sandbox Code Playgroud)

或两个字段:

$ jq '.data.password, .data.username' data.json
"test123"
"testuser1"
Run Code Online (Sandbox Code Playgroud)


Ini*_*ian 6

我会推荐 jq一个轻量级的JSON感知解析器来操作JSON内容。将命令输入通过管道传输curl到过滤器中jq

curl-command | jq --raw-output '.data.password, .data.username'
Run Code Online (Sandbox Code Playgroud)

提供下载和安装jq说明。