Ben
Ben

Reputation: 3357

Rails string of array of hashes with keys - convert to array of hashes

I have this string which I pass with an ajax call from an API response (I cannot alter the data before sending to Rails, since it is done with jQuery in the view)

str = '{"0"=>{"firstName"=>"Testing", "lastName"=>"It", "email"=>"[email protected]"}, "1"=>{"firstName"=>"Tester", "lastName"=>"You", "email"=>"[email protected]"}}'

I want to parse it into a ruby array of hashes.

The most logical parsing with JSON fails:

JSON.parse(str)

JSON::ParserError (765: unexpected token at '{"0"=>{"firstName"=>"Testing", "lastName"=>"It", "email"=>"[email protected]"}, "1"=>{"firstName"=>"Tester", "lastName"=>"You", "email"=>"[email protected]"}}')

Any ideas how to parse this elegantly without gsub or splits. Perhaps convert the string somehow to Ruby array of hashes format somehow?

Upvotes: 0

Views: 494

Answers (2)

arieljuod
arieljuod

Reputation: 15838

Since that's a ruby hash, you can use eval

hash = eval(str)

Upvotes: 2

Ben
Ben

Reputation: 3357

Thanks Hayden for pointing this out! Indeed I was passing an invalid JSON because I was passing the object and not the JSON. Solved by passing the array object from the view with JSON.stringify

Upvotes: 0

Related Questions