Encode a Ruby string to a JSON string

Viewed 42726

The json gem does not allow for directly encoding strings to their JSON representation. I tentatively ported this PHP code:

$text = json_encode($string);

to this Ruby:

text = string.inspect

and it seemed to do the job but for some reason if the string itself contains a literal string (it's actually JS code) with newlines, these newlines \n will stay as-is \n, not be encoded to \\n. I can understand if this is the correct behaviour of #inspect, but...

How does one encode a string value to its JSON representation in Ruby?

3 Answers
Related