Thursday, February 28, 2013

Ruby's Opinion on JSON Handling

This is just beautiful:
$ irb
>> require 'json'
=> true
>> a={123=>"number","123"=>"string",:"123"=>"symbol"}
=> {"123"=>"string", :"123"=>"symbol", 123=>"number"}
>> JSON.unparse(a)
=> "{\"123\":\"string\",\"123\":\"symbol\",\"123\":\"number\"}"
>> JSON.parse(JSON.unparse(a))
=> {"123"=>"number"}
So apparently the standard JSON gem in Ruby thinks that it is ok to convert - without errors - a hash with a bunch of non-string keys into a hash with string keys where the converted-to-string keys collide.

I can see no advantage for this to work this way. It should throw an exception when attempting the unparse operation.

On the other hand I am actually ok that parsing {\"123\":\"string\",\"123\":\"symbol\",\"123\":\"number\"}" works without generating errors. The parser should try to do whatever it can to interpret the data. That said, it would be nice if it was possible to also turn on a "strict" mode where any issue of this sort would be detected and reported.

I understand this was an implementation choice. It would not have been my choice.

No comments:

Post a Comment