Prevent JSON pretty_generate from exiting Unicode

Is there any way to prevent using the Ruby method JSON.pretty_generate()for a Unicode character?

I have a JSON object as follows:

my_hash = {"my_str" : "\u0423"};

A run JSON.pretty_generate(my_hash)returns the value as \\u0423.

Is there a way to prevent this behavior?

+5
source share
2 answers

In your question you have a string of Unicode characters 6 "\", "u", "0", "4", "2", "3"( my_hash = { "my_str" => '\u0423' }), rather than a string of 1 ""character ( "\u0423", note the double quotes).

RFC 4627, 2.5, JSON , JSON.pretty_generate.

, escape- . , , , , "\\".

char = unescaped /
       escape (...
           %x5C /          ; \    reverse solidus U+005C

escape = %x5C              ; \

, JSON ruby ​​gem , JSON JSON.pretty_generate.

JSON gem - '\' char:

module JSON
    MAP = {
        ...
        '\\'  =>  '\\\\'

JSON gem gem install json_pure ( , C, gem install json).

: JSON, , , :

my_hash = { "my_str" => '\u0423' }
# => {"my_str"=>"\\u0423"}

json = JSON.pretty_generate(my_hash)
# => "{\n  \"my_str\": \"\\\\u0423\"\n}"

res = json.gsub "\\\\", "\\"
# => "{\n  \"my_str\": \"\\u0423\"\n}"

, !

+4

=>, :. , 1.9: my_hash = {my_str: "\u0423"}. :my_str.

, JSON.pretty_generate , :

irb(main):002:0> my_hash = {"my_str" => "\u0423"}
=> {"my_str"=>""}
irb(main):003:0> puts JSON.pretty_generate(my_hash)
{
  "my_str": ""
}
=> nil

Ruby 1.9.2p290, () json 1.4.2.

+2

All Articles