RFC 4627:JavaScript 对象表示法 (JSON) 的 application/json 媒体类型 http://www.ietf.org/rfc/rfc4627.txt有这样说:
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
如果你打电话to_json
在您的六个样本对象上,我们得到:
>> objects = [ {}, [], 42, "", true, nil ]
>> objects.map { |o| puts o.to_json }
{}
[]
42
""
true
null
所以第一个和第二个是有效的JSON 文本而后四个无效JSON 文本即使它们是有效的JSON 值.
JSON.parse http://flori.github.com/json/doc/classes/JSON.html#M000061想要所谓的 JSON 文档:
解析 JSON 文档source转换为 Ruby 数据结构并返回它。
Perhaps 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
正如您在评论中指出的那样,使用数组作为包装器比对象更好,以防调用者想要使用:symbolize_names
选项。像这样包裹意味着你会一直在吃东西JSON.parse
JSON 文本,一切都应该没问题。