此代码段引发异常:
x = nil
jsoned = x.to_json
puts 'x.to_json=' + jsoned.inspect
puts 'back=' + JSON.parse(jsoned).inspect
C:/ruby/lib/ruby/1.9.1/json/common.rb:146:in `parse': 706: unexpected token at 'null' (JSON::ParserError)
x.to_json="null"
from C:/ruby/lib/ruby/1.9.1/json/common.rb:146:in `parse'
from C:/dev/prototyping/appoxy_app_engine/test/temp.rb:10:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
Run Code Online (Sandbox Code Playgroud)
这是预期的行为吗?我认为这应该有效吗?
Kar*_*ley 16
JSON解析器有一个"怪癖模式",它将解析单个JSON值.
>> nil.to_json
=> "null"
>> JSON.parse("null", {:quirks_mode => true})
=> nil
Run Code Online (Sandbox Code Playgroud)
它也适用于其他单个值:
>> JSON.parse("12", {:quirks_mode => true})
=> 12
>> JSON.parse("true", {:quirks_mode => true})
=> true
>> JSON.parse(" \"string\" ", {:quirks_mode => true})
=> "string"
Run Code Online (Sandbox Code Playgroud)
问题不在于此nil.它是to_json像一个简单的事情nil或者一个字符串不会产生一个完整的JSON表示.
例如,JSON.parse("hello".to_json)会产生类似的结果
如果我们对其中一个值有一个Hashwith nil,它将正确编码和解码:
>> h = {"name"=>"Mike", "info"=>nil}
=> {"name"=>"Mike", "info"=>nil}
>> h.to_json
=> "{\"name\":\"Mike\",\"info\":null}"
>> JSON.parse(h.to_json)
=> {"name"=>"Mike", "info"=>nil}
Run Code Online (Sandbox Code Playgroud)