仅使用 Bash 解析 JSON

Parse through JSON using only Bash

我有一个 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
}

我正在尝试读取 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

但是因为我只想使用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

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

我建议使用 jq:

$ jq '.data.password' data.json
"test123"

或两个字段:

$ jq '.data.password, .data.username' data.json
"test123"
"testuser1"

我会推荐 jq 一个轻量级 JSON 感知解析器来处理 JSON 内容。将您的 curl 命令输入管道到 jq 中的过滤器,如

curl-command | jq --raw-output '.data.password, .data.username'

download-and-install jq 的说明可用。

您可以使用bashJson

它是 Python 的 JSON 模块的包装器,可以处理复杂的 JSON 数据。

在这里查看我的回答,例如用法: