Ryan-Neal Mes Ryan-Neal Mes - 1 year ago 163
JSON Question

Why is `JSON.parse` not throwing exception?

We have been using JSON.parse for a while now and we just updated to the latest version.

We are getting the following error.

Has the functionality been updated to return nil instead of throwing a ParserError?

2.3.0 :001 > gem 'json', '2.0.2'
=> true
2.3.0 :002 > require 'json'
=> true
2.3.0 :003 > JSON.parse("null")
=> nil

2.3.0 :001 > gem 'json', '1.8.3'
=> true
2.3.0 :003 > require 'json'
=> true
2.3.0 :004 > JSON.parse("null")
JSON::ParserError: 784: unexpected token at 'null'
from /Users/ryannealmes/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/json/common.rb:156:in `parse'
from /Users/ryannealmes/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/json/common.rb:156:in `parse'
from (irb):4
from /Users/ryannealmes/.rvm/rubies/ruby-2.3.0/bin/irb:11:in `<main>'
2.3.0 :005 >

Answer Source

The functionality has been updated to comply with the JSON specification according to RFC 7159, which says:

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

false null true

The literal names MUST be lowercase. No other literal names are allowed.

So, JSON.parse("null") returning nil is expected functionality, which you can confirm by checking out the tests for parsing single values.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download