Saturday, February 27, 2010

Programmer - Parsing JSON without quoted keys

Programmer Question

I understand that in JSON, keys are supposed to be surrounded in double quotes. However, I'm using a data source which doesn't quote them, which is causing the Ruby JSON parser to raise an error. Is there any way to perform 'non-strict' parsing?



Example:



>> JSON.parse('{name:"hello", age:"23"}')
JSON::ParserError: 618: unexpected token at '{name:"hello", age:"23"}'
from /Library/Ruby/Gems/1.8/gems/json-1.1.7/lib/json/common.rb:122:in `parse'
from /Library/Ruby/Gems/1.8/gems/json-1.1.7/lib/json/common.rb:122:in `parse'
from (irb):5
>> JSON.parse('{"name":"hello", "age":"23"}')
=> {"name"=>"hello", "age"=>"23"}
>>


(I tried using a regular expression to add the quotes in before parsing but couldn't get it fully working).



Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails