Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode a Ruby string to a JSON string

Tags:

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?

like image 976
Félix Saparelli Avatar asked Jul 21 '11 23:07

Félix Saparelli


People also ask

Can I JSON encode a string?

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.

Does Ruby support 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.

What is JSON Ruby?

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.

What is encode in JSON?

The json_encode() function is used to encode a value to JSON format.


1 Answers

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".

like image 174
John Avatar answered Oct 02 '22 23:10

John