A JSON text must at least contain two octets A JSON text must at least contain two octets ruby-on-rails ruby-on-rails

A JSON text must at least contain two octets


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  endendparsed = 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. :-)