使用内置的Ruby JSON库反序列化JSON基元

Phr*_*ogz 6 ruby json

为什么Ruby的内置JSON不能反序列化简单的JSON原语,我该如何解决它?

irb(main):001:0> require 'json'
#=> true

irb(main):002:0> objects = [ {}, [], 42, "", true, nil ]
#=> [{}, [], 42, "", true]

irb(main):012:0> objects.each do |o|
irb(main):013:1*   json = o.to_json
irb(main):014:1>   begin
irb(main):015:2*     p JSON.parse(json)
irb(main):016:2>   rescue Exception => e
irb(main):017:2>     puts "Error parsing #{json.inspect}: #{e}"
irb(main):018:2>   end
irb(main):019:1> end
{}
[]
Error parsing "42": 706: unexpected token at '42'
Error parsing "\"\"": 706: unexpected token at '""'
Error parsing "true": 706: unexpected token at 'true'
Error parsing "null": 706: unexpected token at 'null'
#=> [{}, [], 42, "", true, nil]

irb(main):020:0> RUBY_DESCRIPTION
#=> "ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10.7.0]"
irb(main):022:0> JSON::VERSION
#=> "1.4.2"
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 9

RFC 4627:JavaScript Object Notation(JSON)的application/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

[...]

2.1.  Values

   A JSON value MUST be an object, array, number, or string, or one of
   the following three literal names:

      false null true
Run Code Online (Sandbox Code Playgroud)

如果您调用to_json六个示例对象,我们会得到:

>> objects = [ {}, [], 42, "", true, nil ]
>> objects.map { |o| puts o.to_json }
{}
[]
42
""
true
null
Run Code Online (Sandbox Code Playgroud)

所以第一个和第二个是有效的JSON文本,而后四个不是有效的JSON文本,即使它们是有效的JSON值.

JSON.parse 想要它所谓的JSON文档:

将JSON文档源解析为Ruby数据结构并将其返回.

也许JSON文档是RFC 4627称为JSON文本的库的术语.如果是这样,那么引发异常是对无效输入的合理响应.

如果你强行包装和解开所有东西:

objects.each do |o|
    json = o.to_json 
    begin
        json_text = '[' + json + ']'
        p JSON.parse(json_text)[0]
    rescue Exception => e 
        puts "Error parsing #{json.inspect}: #{e}"    
    end    
end
Run Code Online (Sandbox Code Playgroud)

正如您在评论中所述,在调用者想要使用该:symbolize_names选项的情况下,使用数组作为包装器比对象更好.这样包装意味着你总是会提供JSON.parse一个JSON文本,一切都应该没问题.