2

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\"=>\"\"}]"
3
  • 2
    That's not JSON. That's the result of some_array_of_hashes.inspect. Where are you getting that string? Can you tell the source to be more sensible? Commented May 4, 2015 at 20:44
  • 1
    As @muistooshort said, that isn't JSON. We can't help unless you give us correct input. As is your question is unclear (actually more like nonsense) so we need to see the real incoming JSON string. JSON is extremely easy to work with so you'd probably be helped by reading other Ruby/JSON related questions. Commented May 4, 2015 at 21:08
  • Thanks to everyone for your help. This structure is what was being saved to the database from my form. It turns out that I needed to serialize the output before saving. After doing that, the string saved to the database is in proper json format (with no hash rocket). Commented May 5, 2015 at 14:14

3 Answers 3

4

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"=>""}] 
Sign up to request clarification or add additional context in comments.

Comments

2

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"=>""}] 

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.