简体   繁体   中英

Bash: How to escape a string for use in JSON?

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.

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"
}

" JSON strings can not contain line feeds ", as oguz ismail already mentioned, so it's better to let dedicated tools like xidel (or jq ) convert the line feeds to a proper escape sequence and to valid JSON.

Stdin:

$ var='Hello
    "world". 
    This is \anything \or \nothing
'

$ xidel - -se '{"var":$raw}' <<< "$var"
{
  "var": "Hello\n    \"world\". \n    This is \\anything \\or \\nothing\n"
}

Environment variable:

$ export var='Hello
    "world".
    This is \anything \or \nothing
'

$ xidel -se '{"var":environment-variable("var")}'
{
  "var": "Hello\n    \"world\". \n    This is \\anything \\or \\nothing\n"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM