Is there any way to prevent Ruby’s JSON.pretty_generate() method from escaping a Unicode character?
I have a JSON object as follows:
my_hash = {"my_str" : "\u0423"};
Running JSON.pretty_generate(my_hash) returns the value as being \\u0423.
Is there any way to prevent this behaviour?
In your question you have a string of 6 unicode characters
"\","u","0","4","2","3"(my_hash = { "my_str" => '\u0423' }), not a string consisting of 1"У"character ("\u0423", note double quotes).According to RFC 4627, paragraph 2.5, backslash character in JSON string must be escaped, this is why your get double backslash from
JSON.pretty_generate.Thus JSON ruby gem escape this character internally and there is no way to alter this behavior by parametrizing
JSONorJSON.pretty_generate.If you are interested in JSON gem implementation details – it defines internal mapping hash with explicit mapping of ” char:
I took this code from a pure ruby variant of JSON gem
gem install json_pure(note that there are also C extension variant that is distributed bygem install json).Conclusion: If you need to unescape backslash after JSON genaration you need to implement it in your application logic, like in the code above:
Hope this helps!