在rails中解码JSON简单字符串引发错误

msh*_*onj 12 json ruby-on-rails

我正试图在json中往返编码/解码普通字符串,但是我收到了一个错误.

在轨道2.3.w/ruby​​ 1.8.6,它曾经工作过.

>> puts ActiveSupport::JSON.decode("abc".to_json)
abc
=> nil
Run Code Online (Sandbox Code Playgroud)

在rails 3.1beta1 w/ruby​​ 1.9.2中,它会引发错误.

ruby-1.9.2-p180 :001 > puts ActiveSupport::JSON.decode("abc".to_json)
MultiJson::DecodeError: 706: unexpected token at '"abc"'
    from /home/stevenh/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/json/common.rb:147:in `parse'
    from /home/stevenh/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/json/common.rb:147:in `parse'
    from /home/stevenh/.rvm/gems/ruby-1.9.2-p180/gems/multi_json-1.0.1/lib/multi_json/engines/json_gem.rb:13:in `decode'
    [...]
Run Code Online (Sandbox Code Playgroud)

这与nil.to_json讨论的问题几乎相同,无法解析为nil?

但是nil曾经在2.3/1.8.7中工作过.

puts ActiveSupport::JSON.decode(nil.to_json)
nil
Run Code Online (Sandbox Code Playgroud)

这是新常态吗?

Yar*_*boy 8

从ActiveSupport的JSON后端切换到 Rails 3.1.0.rc1中包含的MultiJson时发生了这种变化.根据MultiJson项目团队,由于RFC4627对JSON语法的规范,当前行为是正确的并且之前的实现是错误的:

2.  JSON Grammar

   A JSON text is a sequence of tokens.  The set of tokens includes six
   structural characters, strings, numbers, and three literal names.

   A JSON text is a serialized object or array.

      JSON-text = object / array
Run Code Online (Sandbox Code Playgroud)

既不是序列化对象"abc"也不"/"abc/""是序列化对象或数组,尝试解码它们时出错是合适的.

JSON网站上的图表强化了此规范.

话虽这么说,这似乎意味着to_json实现中的一个错误导致:

ruby-1.9.2-p180 :001 > "abc".to_json
 => "\"abc\""
Run Code Online (Sandbox Code Playgroud)