0

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?

2
  • 3
    That's not valid JSON. JSON would have colons (:) where this has the "=>" operator. Either figure out how to get proper JSON from the API or gsub the "=>" for ":" Commented Feb 16, 2019 at 19:28
  • It is not clear what array you want. The string you have, which is not a valid JSON, could be interpreted as Ruby, in which case it would be a hash, not an array of hashes. Commented Feb 19, 2019 at 9:54

2 Answers 2

2

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

hash = eval(str)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @arieljuod, I didn't know about eval. It works as well. So both the answers are true in this case, however, I believe Hayden's comment is the most effective suggesting to avoid sending the data in the wrong format in the first place. Thanks for sharing your solution!
0

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

1 Comment

This is not an answer to the question. If the question has turned out to be an XY-question, and you have solved it in another way, write that perhaps as a comment to your question, or addition to your question, not as an independent answer here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.