Issue
My Bash script has lots of variable assignments which are put in a JSON file:
var='Hello
"world".
This is \anything \or \nothing
'
echo "{ \"var\"= \"$var\" }" > output.json
When validating the file output.json
jq says:
$ cat output.json | jq .
parse error: Invalid numeric literal at line 1, column 9
How can I make a valid JSON file out of it? Any \
and "
should be preserved.
The correct JSON string would be
{ "var": "Hello
\"world\".
This is \\anything \\or \\nothing
" }
I cannot modify the variable assignments but the JSON creation.
Solution
Pass $var
as a raw string argument and JQ will automatically convert it to a valid JSON string.
$ jq -n --arg var "$var" '{$var}'
{
"var": "Hello\n \"world\". \n This is \\anything \\or \\nothing\n"
}
Answered By - oguz ismail Answer Checked By - Clifford M. (WPSolving Volunteer)