MultiJson.load('') behavior doesn't match JSON specification
joshcooper opened this issue · 2 comments
MultiJson.load('')
raises, but JSON.load('')
returns nil
:
require 'json'
puts JSON.load('').inspect
require 'multi_json'
MultiJson.use(:json_gem)
begin
puts MultiJson.load('')
rescue => e
puts e.class
end
$ bx ruby --version
ruby 2.7.6p219 (2022-04-12 revision c9c2245c0a) [x86_64-linux]
$ bx ruby test.rb
nil
MultiJson::ParseError
MultiJson behavior was changed in 49aa2d8 to raise an error. But JSON has accepted empty string since 2011 ruby/json@0eb6ed5 Also the spec says:
A [JSON] string is a sequence of zero or more Unicode characters
It appears JSON.load
accepts an empty string by default, but JSON.parse
and MultiJson.load
do not. Also JSON.parse
can be configured to reject empty strings:
irb(main):001:0> require 'json'
=> true
irb(main):002:0> JSON.load("")
=> nil
irb(main):003:0> JSON.load("", nil, allow_blank: true)
=> nil
irb(main):004:0> JSON.load("", nil, allow_blank: false)
Traceback (most recent call last):
....
3: from /home/josh/work/json/lib/json/common.rb:569:in `load'
2: from /home/josh/work/json/lib/json/common.rb:216:in `parse'
1: from /home/josh/work/json/lib/json/common.rb:216:in `parse'
JSON::ParserError (783: unexpected token at '')
irb(main):005:0> JSON.parse("")
Traceback (most recent call last):
...
2: from /home/josh/work/json/lib/json/common.rb:216:in `parse'
1: from /home/josh/work/json/lib/json/common.rb:216:in `parse'
JSON::ParserError (783: unexpected token at '')
I think it would be least surprising if MultiJson.load
allowed an empty string like the similarly named JSON.load
, but I don't know if that behavior is universal among different backends.
I would accept a patch to make MultiJson.load
behave like JSON.load
, however this would require a major version bump.