1

I have a JSON file and I'm trying to add another field to it.

Example JSON File:

{"data":{}}

Looking at other answers the += seems to work:

objectName="objName"
cat $jsonFile | jq --arg objName $objectName '.data[$objName] += {"test": "json"}'

Outputs

{
  "data": {
    "objName": {
      "test": "json"
    }
  }
}

just as expected.

The problem is that I can't hardcode the JSON so I'm inputting the string as a variable. But I can't get the syntax to work:

objectName="objName"
objJSON='{"test": "json"}'
cat $jsonFile | jq -r --arg objName $objectName --arg jsonString $objJSON '.data[$objName] += $jsonString'

I'm getting the error jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Unix shell quoting issues?) at <top-level>, line 1: "json"}

0

1 Answer 1

2
  1. Use --argjson rather than --arg when passing JSON rather than strings.

  2. When in doubt, quote your strings; that way if the shell executing your code isn't the one you think it is, you won't have your values being munged. (It's also helpful to stay in the habits necessary to write portable code; the whole reason I dropped zsh after spending 6 months learning it back in the mid-2000s is that my code quality when writing for other shells suffered).


objName="objName"
objJSON='{"test": "json"}'
echo '{"data":{}}' |
  jq --arg     objectName "$objName" \
     --argjson jsonString "$objJSON" \
    '.data[$objectName] += $jsonString'

...properly emits:

{
  "data": {
    "objName": {
      "test": "json"
    }
  }
}
Sign up to request clarification or add additional context in comments.

9 Comments

Hmmm with this I get jq: invalid JSON text passed to --argjson Use jq --help for help with command-line options
objJSON='{"test": "json"}'
hold on I think my Json is capitalized differently than yours
Run set -x to tell your shell to enable tracing so you can see the arguments it's actually passing.
|

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.