Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 >
like image 805
Ryan-Neal Mes Avatar asked Jun 27 '26 22:06

Ryan-Neal Mes


1 Answers

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.

like image 136
Paul Fioravanti Avatar answered Jun 29 '26 23:06

Paul Fioravanti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!