简体   繁体   English

JQ json 中的条件变量取决于参数值?

[英]Conditional variables in JQ json depending on argument value?

I am trying to build a json with jq with --arg arguments however I'd like for the json not to be able to have a condition if the variable is empty.我正在尝试使用带有 --arg 参数的 jq 构建一个 json,但是如果变量为空,我希望 json 不能有条件。

An example, if I run the following command一个例子,如果我运行以下命令

jq -n --arg myvar "${SOMEVAR}" '{ $myvar}'

I'd like the json in that case to be {} if myvar happens to be empty (Because the variable ${SOMEVAR} does not exist) and not { "myvar": "" } which is what I get by just running the command above.如果 myvar 碰巧为空(因为变量 ${SOMEVAR} 不存在),我希望在这种情况下的 json 是{}而不是{ "myvar": "" }这就是我通过运行得到的上面的命令。

Is there any way to achieve this through some sort of condition?有没有办法通过某种条件来实现这一目标?

UPDATE:更新:

Some more details about the use case有关用例的更多详细信息

I want to build a json based on several environment variables but only include the variables that have a value.我想基于多个环境变量构建一个 json,但只包含具有值的变量。

Something like就像是

{"varA": "value", "varB": "value"}

But only include varA if its value is defined and so on.但是只有在定义了 varA 的值时才包含它,依此类推。 The issue now is that if value is not defined, the property varA will still exist with an empty value and because of the multiple argument/variable nature, using an if/else to build the entire json as suggested will lead to a huge amount of conditions to cover for every possible combination of variables not existing现在的问题是,如果没有定义 value,属性varA仍然会以空值存在,并且由于多个参数/变量的性质,按照建议使用 if/else 构建整个 json 将导致大量条件来覆盖不存在的所有可能的变量组合

Suppose you have a template of variable names, in the form of an object as you have suggested you want:假设您有一个变量名称模板,采用您所建议的对象形式:

{a, b, c}

Suppose also (for the sake of illustration) that you want to pull in the corresponding values from *ix environment variables.还假设(为了说明起见)您想从 *ix 环境变量中提取相应的值。 Then you just need to adjust the template, which can be done using this filter:然后你只需要调整模板,这可以使用这个过滤器来完成:

def adjust: with_entries( env[.key] as $v | select($v != null) | .value = $v );

Example:例子:

Assuming the above filter, together with the following line, is in a file named adjust.jq:假设上述过滤器以及以下行位于名为 adjust.jq 的文件中:

 {a,b,c} | adjust

then:然后:

 $ export a=123
 $ jq -n -f -c adjust.jq 
 {"a":"123"}

您可以使用if/else结构:

jq -n --arg myvar "${SOMEVAR}" 'if ($myvar|length > 0) then {$myvar} else {} end'

仍然不清楚变量-值对来自哪里,所以在调用 jq 之前构造包含映射的对象,然后使用 --argjson 或 --argfile 选项将其传入可能是最简单的?

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

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