Josh Hunter
Josh Hunter

Reputation: 1687

JSON parse a string of an array of hashes

I'm having trouble wrapping my head around how to parse this string. I've never really used the JSON.parse method and feel like I'm getting nowhere with it.

"[{\"name\"=>\"memorial hospital\", \"number\"=>\"555-555-1212\"}, {\"name\"=>\"other name hospital\", \"number\"=>\"345-234-2342\"}, {\"name\"=>\"\", \"number\"=>\"\"}]"

Upvotes: 2

Views: 4667

Answers (3)

Abdul Baig
Abdul Baig

Reputation: 3721

Here is the possible work arround:

first convert it to proper json by doing:

s = s.gsub('=>', ':')

then parse it by

JSON.parse s

the output should be:

=> [{"name"=>"memorial hospital", "number"=>"555-555-1212"}, {"name"=>"other name hospital", "number"=>"345-234-2342"}, {"name"=>"", "number"=>""}] 

Upvotes: 4

pete
pete

Reputation: 162

If you are new to json, there are some good free online json parsers/validators you can use to test your json... http://json.parser.online.fr/ http://jsonlint.com/

Note, you will need to remove the escape character ('\') for these parsers to work.

In this particular case, you can fix your json text by replacing '=>' with ':' within your json text.

Upvotes: 1

Myst
Myst

Reputation: 19221

I think your string is malformed.

The JSON string wouldn't have =>. The key=>value should look like key:value.

Try the following string:

"[{\"name\":\"memorial hospital\", \"number\":\"555-555-1212\"}, {\"name\":\"other name hospital\", \"number\":\"345-234-2342\"}, {\"name\":\"\", \"number\":\"\"}]"

This should work:

require 'json'
s = "[{\"name\":\"memorial hospital\", \"number\":\"555-555-1212\"}, {\"name\":\"other name hospital\", \"number\":\"345-234-2342\"}, {\"name\":\"\", \"number\":\"\"}]"

JSON.parse s
#  => [{"name"=>"memorial hospital", "number"=>"555-555-1212"}, {"name"=>"other name hospital", "number"=>"345-234-2342"}, {"name"=>"", "number"=>""}] 

Upvotes: 2

Related Questions