0

I am trying to use curl to submit a request that requires one of the parameters to be an integer. I want to be able to use a variable for that integer, but can't figure out how to do it without it showing up as a string or failing to substitute the variable in.

stringVar="L"
intVar=4

JSON=\''{"stringVar": "'"$stringVar"'","intVar": "'"$intVar"'" }'\'


printf '%s\n' "$JSON"

I have tried all the combinations I can think of of quotes no quotes and braces and can't figure it out.

3
  • Can you post the desired result? Commented Jan 6, 2020 at 18:35
  • I don't agree with this question being a duplicate of the two linked. stackoverflow.com/questions/48470049/… This one doesn't answer the main problem I had with generating a json string with an integer. stackoverflow.com/questions/48887711/… This question asks about how to do it when using a specific tool. Commented Jan 6, 2020 at 19:55
  • The second fills in information missing from the first. Combine them, and you have a duplicate. Which is to say, I didn't mean to imply via the flagging that it was a duplicate of each preexisting question individually, but rather that we have multiple narrower preexisting questions that, combined, add up to the same thing. Commented Jan 7, 2020 at 3:54

1 Answer 1

2

Do not ever generate JSON with string concatenation. The result is not guaranteed to be valid JSON (which any and every compliant parser will accept) unless it's generated by a compliant generator. For bash, one of the most widely-available tools for both purposes is jq:

# taken from the question
stringVar="L"; intVar=4

json=$(jq -n \
          --arg stringVar "$stringVar" \
          --arg intVar "$intVar" \
          '{"stringVar": $stringVar, "intVar": $intVar | tonumber}')
Sign up to request clarification or add additional context in comments.

7 Comments

Code above leads to jq: error (at <unknown>): Expected JSON value (while parsing '').
Tested with jq-1.6 also. I did copy-and-paste as well.
@accdias, did you set the OP's stringVar and intVar first?
Heh. Yeah, trying to parse an empty string as an integer (as $intVar | tonumber does when intVar is empty, or otherwise not a number) will fail explicitly rather than generate incorrect JSON (as it would with the original code). That's a feature, not a bug. :)
@Corey, it only works without quotes while your test cases are simple. Change it to stringVar='*' or even just stringVar='two words' and then --arg stringVar $stringVar won't work anymore. (In general, bash is full of those kinds of subtle pitfalls, so trying to figure out what's "right" by trial-and-error is perilous; see BashPitfalls and the BashFAQ for more examples of cases where robust answers are nonobvious).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.