title: Bash: How to escape a string for use in JSON?
body: <p>My Bash script has lots of variable assignments which are put in a JSON file:</p>
  
  <pre><code>var='Hello
      "world". 
      This is \anything \or \nothing
  '
  echo "{ \"var\"= \"$var\" }" &gt; output.json
  </code></pre>
  
  <p>When validating the file <code>output.json</code> jq says:</p>
  
  <pre><code>$ cat output.json | jq .
  parse error: Invalid numeric literal at line 1, column 9
  </code></pre>
  
  <p>How can I make a valid JSON file out of it? Any <code>\</code> and <code>"</code> should be preserved.</p>
  
  <p>The correct JSON string would be</p>
  
  <pre><code>{ "var": "Hello
      \"world\". 
      This is \\anything \\or \\nothing
    " }
  </code></pre>
  
  <p>I cannot modify the variable assignments but the JSON creation.</p>