仅使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:09:26  来源:igfitidea点击:

Parse through JSON using only Bash

jsonbashsedcut

提问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 usernameand password. Now I was able to integrate bash and python to get what I wanted.

我想读的价值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

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 sedand cutcommands correctly in this case. Or is there a better way to extract the required fields?

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

回答by grundic

I would recommend using jq:

我建议使用jq

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

Or both fields:

或两个字段:

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

回答by Inian

I would recommend jqa lightweight JSONaware parser for manipulating JSONcontent. Pipe your curlcommand input to a filter in jqas

我会推荐 jq一个轻量级的JSON解析器来操作JSON内容。管你的curl命令输入到一个过滤器jq作为

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

Instructions to download-and-install jqavailable.

提供下载和安装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