A JSON text must at least contain two octets

谁说我不能喝 提交于 2019-11-29 20:49:54
parsed = json && json.length >= 2 ? JSON.parse(json) : nil

But really the library should be able to handle this case and return nil. Web browsers with built-in JSON support seem to work just like you expect after all.


Or to do it with a only slightly intrusive mini patch:

module JSON
  def self.parse_nil(json)
    JSON.parse(json) if json && json.length >= 2
  end
end

parsed = JSON.parse_nil(json)
data.presence && JSON.parse(data)

JSON.parse(data.presence || '{}')

According to json.org

JSON is built on two structures:

  1. A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

  2. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

So, minimum two octets(8 bits) required at the top level would be {} or []

IMO, the best solution would be to make sure the argument to JSON.parse is either an strigified object or a strigified array. :-)

hash = JSON.parse(json) rescue {}
array = JSON.parse(json) rescue []
string = JSON.parse(json) rescue ''
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!