Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON without quoted keys

Tags:

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).

like image 431
Andy Waite Avatar asked Jan 13 '10 21:01

Andy Waite


People also ask

Do JSON keys have to be quoted?

JavaScript object literals do not require quotes around a key name if the key is a valid identifier and not a reserved word. However, JSON always requires quotes around key names.

Can JSON have value without key?

Keys must be strings, and values must be a valid JSON data type: string.

How do I remove quotes from JSON Stringify?

That makes the regex to remove the quotes from the keys MUCH easier. Start your solution with this: var cleaned = JSON. stringify(x, null, 2);

Can JSON have non string keys?

In JSON, the “keys” must always be strings. Each of these pairs is conventionally referred to as a “property”. In Python, "objects" are analogous to the dict type. An important difference, however, is that while Python dictionaries may use anything hashable as a key, in JSON all the keys must be strings.


1 Answers

If the data is pretty well formed other than that, a simple regex might do it:

irb(main):009:0> '{name:"hello", age:"23"}'.gsub(/([a-z]+):/, '"\1":') => "{\"name\":\"hello\", \"age\":\"23\"}" 
like image 74
tfwright Avatar answered Sep 21 '22 17:09

tfwright