[英]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.以这种方式存储的原因是因为当我从 json 存储数据时,我必须将操作参数中包含的内容转换为 hash。
I took a look at How to convert a ruby hash object to JSON?我看了一下如何将 ruby hash object 转换为 Z0ECD11C1D7A287401D148A23BBD? and Parse JSON in JavaScript?
并在 JavaScript 中解析 JSON? , 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}
.首先,问题是 JSON 似乎没有解析任何用双引号括起来的东西,也没有用火箭 hash 表示法,所以我无法转换为转换
"{"x"=>15, "y"=>7}"
到{"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?也许,我必须序列化 object,看看我从哪里得到我的数据: 如何在我的参数中访问通过 JSON 发送的蛇 object 的数据?
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.您无法转换为 JSON 的原因是 hash 火箭不是正确的 JSON 语法。 Hash rocket is purely Ruby syntax.
Hash 火箭纯粹是 Ruby 语法。
What that means is that you somehow managed to take a Hash
and convert it to a String
.这意味着您以某种方式设法获取了
Hash
并将其转换为String
。 So the converted string is actually Ruby code and not JSON.所以转换后的字符串实际上是 Ruby 代码而不是 JSON。
You could do...你可以做...
eval("{\"x\"=>15, \"y\"=>7}")
... and it will return a Ruby Hash
. ...它将返回 Ruby
Hash
。
Or if you don't want to use eval
due to security reasons, you can do...或者,如果您出于安全原因不想使用
eval
,您可以这样做...
JSON.parse("{\"x\"=>15, \"y\"=>7}".gsub('=>', ':'))
Following radiantshaw's lead, using either在 radiantshaw 的带领下,使用任一
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.我得到以下信息:
{"x"=>15, "y"=>7}
,这是 Ruby object。 However in order to convert this to a Javascript object, I also needed to convert it to json.但是,为了将其转换为 Javascript object,我还需要将其转换为 json。
So by taking it one step further, I am able to parse it into json like so:因此,通过更进一步,我可以将其解析为 json ,如下所示:
Put require 'json'
in the.rb file, and then do {"x"=>15, "y"=>7}.to_json
which will result in将
require 'json'
放在 .rb 文件中,然后执行{"x"=>15, "y"=>7}.to_json
这将导致
"{\"x\":15,\"y\":7}"
. "{\"x\":15,\"y\":7}"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.