简体   繁体   English

如何在jq中添加变量

[英]How to add a variable in jq

Im trying to add a variable while getting the info from a json file as shown below.我试图在从 json 文件中获取信息时添加一个变量,如下所示。

stack=$(cat profiles.json | jq '.generic.category')

email=$(cat profiles.json | jq '.central.[Need to add $stack variable here].email')
echo $email
password=$(cat profiles.json | jq '.central.[Need to add $stack variable here].password')
echo $password

I tried few things like jq --arg v $stack '.central[$v]password ' but it didnt work.我尝试了一些类似jq --arg v $stack '.central[$v]password ' 的东西,但它没有用。

This is how my the profiles.json looks like:这就是我的profiles.json的样子:

  "central": {
        "one": {
            "tenant": "xxx-yyy-zzz",
            "email": "xyz@gmail.com",
            "password": "1111"
         },
        "two": {
            "tenant": "aaa-bbb-ccc",
            "email": "xyz@gmail.com",
            "password": "2222"
         }
  },
  "generic": {
        "username": "root",
        "password": "xyz",
        "project": "ABC",
        "category": "two"
    }

What is the right command to fetch the required information using the variable.使用变量获取所需信息的正确命令是什么。

$ cat profiles.json
{
   "central": {
        "one": {
            "tenant": "xxx-yyy-zzz",
            "email": "xyz@gmail.com",
            "password": "1111"
         },
        "two": {
            "tenant": "aaa-bbb-ccc",
            "email": "xyz@gmail.com",
            "password": "2222"
         }
  },
  "generic": {
        "username": "root",
        "password": "xyz",
        "project": "ABC",
        "category": "two"
    }
}

$ jq --arg MYVAR one '.central[$MYVAR].password' profiles.json
"1111"

You can do without the shell variable stack , unless you want to use it in different places later in your shell script.您可以不使用 shell 变量stack ,除非您想稍后在 shell 脚本中的不同位置使用它。

email=$(jq -r '.central[.generic.category].email' profiles.json)
echo $email
password=$(jq -r '.central[.generic.category].password' profiles.json)
echo $password

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM