仅使用 Bash 解析 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44032450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parse through JSON using only Bash
提问by hack4mer
I have a JSON file :
我有一个 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
}
I am trying to read the values of username
and password
. Now I was able to integrate bash and python to get what I wanted.
我想读的价值username
和password
。现在我能够集成 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
But since I only want to use bash, I have done the following too:
但由于我只想使用 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
I am just concerned whether I have made use of sed
and cut
commands correctly in this case. Or is there a better way to extract the required fields?
我只关心我是否利用了sed
与cut
在这种情况下,正确的命令。或者有没有更好的方法来提取所需的字段?
回答by grundic
回答by Inian
I would recommend jq
a lightweight JSON
aware parser for manipulating JSON
content. Pipe your curl
command input to a filter in jq
as
我会推荐 jq
一个轻量级的JSON
解析器来操作JSON
内容。管你的curl
命令输入到一个过滤器jq
作为
curl-command | jq --raw-output '.data.password, .data.username'
Instructions to download-and-install jq
available.
提供下载和安装jq
说明。
回答by hack4mer
You can use bashJson
您可以使用bashJson
Its a wrapper for the Python's JSON module and can handle complex JSON data.
它是 Python 的 JSON 模块的包装器,可以处理复杂的 JSON 数据。
See my answer here for example usage : https://stackoverflow.com/a/51821898/2734348
在此处查看我的答案以获取示例用法:https: //stackoverflow.com/a/51821898/2734348