仅使用Bash解析JSON

时间:2017-05-17 18:35:21

标签: json bash sed cut

我有一个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命令。或者有更好的方法来提取必填字段吗?

3 个答案:

答案 0 :(得分:2)

我建议使用jq

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

或两个字段:

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

答案 1 :(得分:0)

我建议使用jq轻量级JSON感知解析器来操作JSON内容。将您的curl命令输入传输到jq中的过滤器

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

download-and-install jq的说明。

答案 2 :(得分:0)

您可以使用bashJson

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

在这里查看我的答案以获取示例用法:https://stackoverflow.com/a/51821898/2734348