仅使用 Bash 解析 JSON [英] Parse through JSON using only Bash

查看:74
本文介绍了仅使用 Bash 解析 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JSON 文件:

I have a JSON file :

{
    "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 来获得我想要的东西.

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.

# 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,所以我也做了以下操作:

But since I only want to use bash, I have done the following too:

# 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 命令.或者有没有更好的方法来提取所需的字段?

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?

推荐答案

我建议使用 jq:

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

或两个字段:

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

这篇关于仅使用 Bash 解析 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆