1

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?

  • Does this answer your question? [How do I convert a String object into a Hash object?](https://stackoverflow.com/questions/1667630/how-do-i-convert-a-string-object-into-a-hash-object) – Sebastián Palma Jun 08 '20 at 13:23
  • @SebastianPalma, no. I'm not looking to convert my string into a hash object, but rather to JSON. –  Jun 09 '20 at 07:02
  • 1
    That's what the given answer does, and you accepted it. – Sebastián Palma Jun 09 '20 at 07:55
  • 1
    @SebastianPalma, you're right. At first glance I thought it solved my problem, but I needed to take it one step further. I wrote my own answer. –  Jun 15 '20 at 15:51

2 Answers2

1

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}".

0

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('=>', ':'))
radiantshaw
  • 535
  • 1
  • 5
  • 18