0

I would like to add bash variables to a some JSON file with jq. The following method works:

jq --arg VAR "$VAR" '.+{VAR:$VAR}' my.json > my.tmp.json && mv my.tmp.json my.json

with VAR being a bash variable. But as I'm adding many variables I would like to extract a function like the following:

#$1 Variable Name; The entry {"$1": "$($1)"} should be added to my.json
config_add() {
    COMMAND="jq --arg VAR \"\$VAR\" '.+{VAR:\$VAR}' my.json"
    #Replace VAR with the argument
    ${COMMAND//VAR/$1} my.json > my.json.tmp && my.json.tmp my.json
}

But for any variant I try I receive:

jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Unix shell quoting issues?) at <top-level>, line 1:'.+{MYVAR:$MYVAR}'

Any Ideas what is happening here? How would one quote it correctly? Thank you!

0

1 Answer 1

2

If the strategy you have in mind depends on a bash function having access to global variables, then it would be better to adopt an alternative approach, such as illustrated here:

config_add() {
    local VAR="$1"
    local VALUE="$2"
    jq --arg VAR "$VAR" --arg VALUE "$VALUE" '.+{($VAR): $VALUE}' > my.json.tmp && my.json.tmp my.json 
}

Invocation examples

x=myvar
myvar=foo

config_add x "$x"

config_add "$x" "${!x}"

For the record

export x=xyzzy
jq -n --arg a x '{($a): $ENV[$a]}'
{
  "x": "xyzzy"
}
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.