0

Am trying to add a json array with just one array element to a json. And it has to be added only if it does not already exist. Example json is below.

{
    "lorem": "2.0",
    "ipsum": {
        "key1": "value1",
        "key2": "value2"
    },
    "schemes": ["https"],
    "dorum" : "value3" 
}

Above is the json, where "schemes": ["https"], exists. Am trying to add schemes only if it does not exist using the below code.

scheme=$( cat rendertest.json | jq -r '. "schemes" ')
echo $scheme
schem='["https"]'
echo "Scheme is"
echo $schem
if [ -z $scheme ]
then
echo "all good"
else 
jq --argjson argval  "$schem"  '. += { "schemes" : $schem }' rendertest.json > test.json
fi

I get the below error in a file when the json array element 'schemes' does not exist. It returns a null and errors out. Any idea where am going wrong?

null
Scheme is
["https"]
jq: error: schem/0 is not defined at <top-level>, line 1:
. += { "schemes" : $schem }                   
jq: 1 compile error

Edit: the question is not about how to pass on bash variables to jq.

0

1 Answer 1

2

Just use an explicit if condition that checks for the attribute schemes in the root level of the JSON structure

schem='["https"]'

After setting the above variable in your shell, run the following filter

jq --argjson argval "$schem" 'if has("schemes")|not then .+= { schemes: $argval } else . end' json

The argument immediately after the --argjson field is the one that needs to be used in the context of jq, but you were trying to use $schem in the context which is incorrect.

You can even go one level further and check even if schemes is present and if it does not contain the value you expect, then make the overwrite. Modify the filter within '..' to

( has("schemes")|not ) or .schemes != $argval )

which can be run as

jq --argjson argval "$schem" 'if ( (has("schemes")|not) or .schemes != $argval) then (.schemes: $argval) else . end'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.