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?
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.
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" } ]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With