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?
These values (namely value1,value2, value3,...) can contain any special characters. JSON is an acronym for JavaScript Object Notation , so your asking if there is a JS way to encode/decode a JavaScript Object from and to a string? The answer is yes: JSON.
JSON is directly supported in Ruby, and has been since at least Ruby v1. 9.3, so there is no need to install a gem unless you're using something older. Simply use require 'json' in your code.
Ruby Language JSON with Ruby Using JSON with Ruby JSON (JavaScript Object Notation) is a lightweight data interchange format. Many web applications use it to send and receive data. In Ruby you can simply work with JSON. At first you have to require 'json' , then you can parse a JSON string via the JSON.
The json_encode() function is used to encode a value to JSON format.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With