json 将参数传递给 jq 过滤器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34745451/
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-03 18:13:35  来源:igfitidea点击:

passing arguments to jq filter

jsonbashparameter-passingjq

提问by lisi4ok

Here is my config.json:

这是我的 config.json:

{
    "env": "dev",
    "dev": {
        "projects" : {
            "prj1": {
                "dependencies": {},
                "description": ""
            }
        }
    }
}

Here are my bash commands:

这是我的 bash 命令:

PRJNAME='prj1'

echo $PRJNAME

jq --arg v "$PRJNAME" '.dev.projects."$v"' config.json 
jq '.dev.projects.prj1' config.json 

The output:

输出:

prj1
null
{
  "dependencies": {},
  "description": ""
}

So $PRJNAME is prj1, but the first invocation only outputs null.

所以 $PRJNAME 是 prj1,但第一次调用只输出null.

Can someone help me?

有人能帮我吗?

回答by

The jq program .dev.projects."$v"in your example will literally try to find a key named "$v". Try the following instead:

.dev.projects."$v"您示例中的 jq 程序将尝试查找名为"$v". 请尝试以下操作:

jq --arg v "$PRJNAME" '.dev.projects[$v]' config.json 

回答by Sebastien DIAZ

you can use too --argjsonwhen you make your json.

--argjson制作 json 时也可以使用。

--arg a v   set variable $a to value <v>;
--argjson a v   set variable $a to JSON value <v>;

回答by LuWa

As asked in a comment above there's a way to pass multiple argumets. Maybe there's a more elegant way, but it works.

正如上面评论中所问的,有一种方法可以传递多个参数。也许有一种更优雅的方式,但它有效。

  • If you are sure always all keys needed you can use this:
  • 如果您确定始终需要所有密钥,则可以使用以下命令:
jq --arg key1 $k1 --arg key2 $k2 --arg key3 $k3 --arg key4 $k4 '.[$key1] | .[$key2] | .[$key3] | .[$key4] '


  • If the key isn't always used you could do it like this:
  • 如果不总是使用密钥,您可以这样做:
jq --arg key $k ' if key != "" then .[$key] else . end'


  • If key sometimes refers to an array:
  • 如果 key 有时指的是一个数组:
jq --arg key $k ' if type == "array" then .[$key |tonumber] else .[$key] end'

of course you can combine these!

当然你可以结合这些!