Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON string to hash

I have a Ruby on Rails JSON question.

I have what I think is a strange error. I have the following JSON string which I get like this from an external API

test = "[{'domain': 'abc.com'}, {'domain': 'def.com'}, {'domain': 'ghi.com'}]"

Now, I want to convert this string to a hash using:

hash = JSON.parse test

The problem is that it errors with:

JSON::ParserError: 419: unexpected token at '{'domain': 'abc.com'}, {'domain': 'def.com'}, {'domain': 'ghi.com'}]'

The problem now with just replacing ' with " is dangerous if any strings includes ' or ". Anyone have a solution?

like image 517
JayC Avatar asked Jan 12 '16 05:01

JayC


3 Answers

It's most likely because this isn't valid JSON. Change your single quotes to double quotes, like so:

test = '[{"domain": "abc.com"}, {"domain": "def.com"}, {"domain": "ghi.com"}]'

An explanation can be found here, and you can validate your JSON here.

like image 119
MyCah Avatar answered Oct 19 '22 18:10

MyCah


You're getting an error because your string isn't valid JSON. In JSON all property names must be double-quoted and string values must also be double-quotes. Single-quotes are never valid.

test = '[{"domain": "abc.com"}, {"domain": "def.com"}, {"domain": "ghi.com"}]'
JSON.parse(test)
# => [ { "domain" => "abc.com" },
#      { "domain" => "def.com" },
#      { "domain" => "ghi.com" } ]
like image 45
Jordan Running Avatar answered Oct 19 '22 17:10

Jordan Running


Using Rails 4 or above, If you want to have symbol keys instead of string keys, you can use deep_symbolize_keys method

hash = JSON.parse(test).deep_symbolize_keys

That's in addition that the real problem was invalid json as MyCah mentioned.

like image 3
Peter T. Avatar answered Oct 19 '22 19:10

Peter T.