简体   繁体   中英

How can I parse these hashes turned string, from my Ruby on Rails API so that it's accessible as an object in Javascript?

The data is stored as an array of objects wrapped in a string that looks like this

["{\"x\"=>15, \"y\"=>7}", "{\"x\"=>14, \"y\"=>7}", "{\"x\"=>13, \"y\"=>7}", "{\"x\"=>13, \"y\"=>6}", "{\"x\"=>13, \"y\"=>5}", "{\"x\"=>13, \"y\"=>4}", "{\"x\"=>13, \"y\"=>3}", "{\"x\"=>12, \"y\"=>3}", "{\"x\"=>11, \"y\"=>3}"] 

The reason it is stored that way is because when I was storing the data from a json, I had to convert what was wrapped in Action Parameters to a hash.

I took a look at How to convert a ruby hash object to JSON? and Parse JSON in JavaScript? , and my answer is not addressed.

First, the problem is that it would seem JSON does not parse anything wrapped in double quotations, nor with rocket hash notation, and so I am not able to convert to convert "{"x"=>15, "y"=>7}" to {"x"=>15, "y"=>7} .

Perhaps, I have to serialize the object, see where I get my data from here: How can I access the data for the snake object sent through JSON in my params?

Any ideas on what the right approach would be?

The reason you're not able to convert to JSON because hash rocket is not a proper JSON syntax. Hash rocket is purely Ruby syntax.

What that means is that you somehow managed to take a Hash and convert it to a String . So the converted string is actually Ruby code and not JSON.

You could do...

eval("{\"x\"=>15, \"y\"=>7}")

... and it will return a Ruby Hash .

Or if you don't want to use eval due to security reasons, you can do...

JSON.parse("{\"x\"=>15, \"y\"=>7}".gsub('=>', ':'))

Following radiantshaw's lead, using either

eval("{\"x\"=>15, \"y\"=>7}")

or

JSON.parse("{\"x\"=>15, \"y\"=>7}".gsub('=>', ':'))

I got the following: {"x"=>15, "y"=>7} , which is a Ruby object. However in order to convert this to a Javascript object, I also needed to convert it to json.

So by taking it one step further, I am able to parse it into json like so:

Put require 'json' in the.rb file, and then do {"x"=>15, "y"=>7}.to_json which will result in

"{\"x\":15,\"y\":7}" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM