tags:

views:

25

answers:

2

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?

+3  A: 

The problem is not specifically with nil. It's that to_json on a simple thing like nil or a single string doesn't produce a full JSON representation.

e.g. something like JSON.parse("hello".to_json) would yield similar results

If we have a Hash with nil for one of its values it will encode and decode correctly:

>> h = {"name"=>"Mike", "info"=>nil}
=> {"name"=>"Mike", "info"=>nil}
>> h.to_json
=> "{\"name\":\"Mike\",\"info\":null}"
>> JSON.parse(h.to_json)
=> {"name"=>"Mike", "info"=>nil}
mikej
A: 

JSON doesn't like single objects, it's really for serializing collections of objects. If you try something like this, you can see that it really does generate valid JSON for nil objects and can de-serialize them.

n = JSON.parse( JSON.generate([nil]) )  # => [nil]
AboutRuby