Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nil.to_json cannot be parsed back to nil?

Tags:

ruby

This snippet throws an exception:

x = nil
jsoned = x.to_json
puts 'x.to_json=' + jsoned.inspect
puts 'back=' + JSON.parse(jsoned).inspect

C:/ruby/lib/ruby/1.9.1/json/common.rb:146:in `parse': 706: unexpected token at 'null'      (JSON::ParserError)
x.to_json="null"
from C:/ruby/lib/ruby/1.9.1/json/common.rb:146:in `parse'
from C:/dev/prototyping/appoxy_app_engine/test/temp.rb:10:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'

Is that expected behavior? I would think this should work?

like image 878
Travis Reeder Avatar asked Aug 23 '10 22:08

Travis Reeder


1 Answers

The JSON parser has a "quirks mode" in which it will parse single JSON values.

>> nil.to_json
=> "null"
>> JSON.parse("null", {:quirks_mode => true})
=> nil

It also works for other single values:

>> JSON.parse("12", {:quirks_mode => true})
=> 12
>> JSON.parse("true", {:quirks_mode => true})
=> true
>> JSON.parse(" \"string\" ", {:quirks_mode => true})
=> "string"
like image 67
Karl Higley Avatar answered Oct 27 '22 16:10

Karl Higley