[英]How can I use JavaScript to parse Ruby JSON string
I'm trying to get the JSON object from a JSON outputted string from a Rails app.我正在尝试从 Rails 应用程序的 JSON 输出字符串中获取 JSON object。 Currently in JavaScript I'm doing:
目前在 JavaScript 我正在做:
data = "<%= @chromosomes.html_safe %>";
However, since there are quotes at the beginning and end of the JSON object, it is not being rendered as a JSON object. Instead it is doing something like但是,由于在 JSON object 的开头和结尾都有引号,因此它不会呈现为 JSON object。相反,它正在做类似的事情
data = "[{"name":"YHet","organism_id":"4ea9b90e859723d3f7000037"}]"
Is there a way that I can remove the beginning and end quotes so that the object is treated as an array instead of a string?有没有一种方法可以删除开始和结束引号,以便将 object 视为数组而不是字符串?
Why don't you do:你为什么不这样做:
data = <%= @chromosomes.html_safe %>;
Sidenote:边注:
I hope you do something like:我希望你做这样的事情:
@chromosomes = [{ name: "YHet", organism_id: "foo" }].to_json
If you are using jQuery you can do the following如果您使用的是 jQuery,您可以执行以下操作
var data = jQuery.parseJSON('[{"name":"YHet","organism_id":"4ea9b90e859723d3f7000037"}]');
Use JSON
object that is included in most of browsers or if you are using jQuery use $.jsonParse
method that try to use JSON
object if defined otherwise parse using eval
or some safer way.使用大多数浏览器中包含的
JSON
object,或者如果您使用的是 jQuery,请使用$.jsonParse
方法,该方法尝试使用JSON
object,否则使用eval
或一些更安全的方式进行解析。
On controller controller
@my_var = MyObj.find_by_id(4).to_json
On page in haml way.以 haml 方式在页面上。
var my_json = $.parseJSON("#{j @my_var}"); //used JQuery to parser JSON string
Use eval:使用评估:
var dataObject = eval('(' + dataString + ')'); var dataObject = eval('(' + dataString + ')');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.