title: Encode a Ruby string to a JSON string
body: <p>The <code>json</code> gem does not allow for directly encoding strings to their JSON representation. I tentatively ported this PHP code:</p>
  
  <pre><code>$text = json_encode($string);
  </code></pre>
  
  <p>to this Ruby:</p>
  
  <pre><code>text = string.inspect
  </code></pre>
  
  <p>and it seemed to do the job but for some reason if the <code>string</code> itself contains a literal string (it's actually JS code) with newlines, these newlines <code>\n</code> will stay as-is <code>\n</code>, not be encoded to <code>\\n</code>. I can understand if this is the correct behaviour of <code>#inspect</code>, but...</p>
  
  <p>How does one encode a string value to its JSON representation in Ruby?</p>