25

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?

Félix Saparelli
  • 8,424
  • 6
  • 52
  • 67

3 Answers3

23

This works with the stock 1.9.3+ standard library JSON:

require 'json'
JSON.generate('foo', quirks_mode: true) # => "\"foo\""

Without quirks_mode: true, you get the ridiculous "JSON::GeneratorError: only generation of JSON objects or arrays allowed".

John
  • 29,546
  • 11
  • 78
  • 79
20

As of Ruby 2.1, you can

require 'json'

'hello'.to_json
Thai
  • 10,746
  • 2
  • 45
  • 57
3

There are a myriad of JSON gems for Ruby, some pure Ruby some C-based for better performance.

Here is one that offers both pure-Ruby and C: http://flori.github.com/json/

And then its essentially:

require 'json'
JSON.encode(something)

A popular JSON encoder/decoder with native C-bindings for performance is Yajl: https://github.com/brianmario/yajl-ruby

UPD from @Stewart: JSON.encode is provided by rails as is object.to_json. For uses outside of rails use JSON.generate which is in ruby 1.9.3 std-lib. – Stewart

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
Cody Caughlan
  • 32,456
  • 5
  • 63
  • 68
  • 1
    As mentioned, the `json` gem __does not allow encoding strings directly__. I'll take a look a Yajl. – Félix Saparelli Jul 21 '11 at 23:25
  • For JSON gem compatibility in yajl you can do `require 'yajl/json_gem'` – mikeycgto Jul 21 '11 at 23:29
  • 11
    It's worth noting that this answer assumes that the question poster is using rails(however this was not stipulated in the question). `JSON.encode` is provided by rails as is `object.to_json`. For uses outside of rails use `JSON.generate` which is in ruby 1.9.3 std-lib. – Stewart Jul 05 '12 at 12:38
  • @Stewart comment should definitely be added to that answer imho – Hezad Nov 25 '12 at 00:51