Alexandre Thenorio
Alexandre Thenorio

Reputation: 2418

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.

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.

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.

Something like

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

But only include varA if its value is defined and so on. 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

Upvotes: 1

Views: 2337

Answers (3)

peak
peak

Reputation: 117017

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. 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:

 {a,b,c} | adjust

then:

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

Upvotes: 1

peak
peak

Reputation: 117017

It's still not clear where the variable-value pairs are coming from, so maybe it would be simplest to construct the object containing the mapping before invoking jq, and then passing it in using the --argjson or --argfile option?

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 158250

You can use an if/else construct:

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

Upvotes: 1

Related Questions