ActiveSupport :: JSON.decode无法正确处理文字换行符

这是预期的行为吗? 注意换行符如何丢失。

ruby-1.9.2-p136 :001 > ActiveSupport::JSON.decode("{\"content\": \"active\n\nsupport\"}") => {"content"=>"active\nsupport"} 

unicode转义换行符也是如此:

 ruby-1.9.2-p136 :002 > ActiveSupport::JSON.decode("{\"content\": \"active\u000a\u000asupport\"}") => {"content"=>"active\nsupport"} 

我正在使用rails 3.0.3。

我最终遇到了这张票: https : //rails.lighthouseapp.com/projects/8994/tickets/3479-activesupportjson-fails-to-decode-unicode-escaped-newline-and-literal-newlines

看来这是ActiveSupport中的一个错误,将在Rails 3.0.5中修复。 现在我修补了activesupport ,事情按预期工作。

 ruby-1.9.2-p136 :001 > ActiveSupport::JSON.decode("{\"content\": \"active\n\nsupport\"}") => {"content"=>"active\n\nsupport"} 

要使用双引号表示JSON数据中的换行符,必须转义换行符:

 ActiveSupport::JSON.decode("{\"content\": \"active\\n\\nsupport\"}") 

否则,您将新行插入JSON 而不是JSON 数据 。 请注意,这也可以:

 ActiveSupport::JSON.decode('{"content": "active\n\nsupport"}') 

通过使用单引号,您不再将文字换行符插入JSON的源代码中。

有趣的是,默认情况下ActiveSupport处理它的方式(默认的JSON后端是ActiveSupport::JSON::Backends::Yaml )。 通过安装json gem并将JSON后端更改为它( ActiveSupport::JSON.backend = 'JSONGem' )并尝试解码相同的文本( ActiveSupport::JSON.decode("{\"content\": \"active\\n\\nsupport\"}") )您得到以下内容:

 JSON::ParserError: 737: unexpected token at '{"content": "active support"}'