I'm trying to get the JSON object from a JSON outputted string from a Rails app. Currently in JavaScript I'm doing:
我正在尝试从Rails应用程序的JSON输出字符串中获取JSON对象。目前在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对象的开头和结尾都有引号,因此它不会呈现为JSON对象。相反,它正在做类似的事情
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?
有没有办法可以删除开头和结尾的引号,以便将对象视为数组而不是字符串?
5 个解决方案
#1
8
Why don't you do:
你为什么不这样做:
data = <%= @chromosomes.html_safe %>;
Sidenote:
I hope you do something like:
我希望你做的事情如下:
@chromosomes = [{ name: "YHet", organism_id: "foo" }].to_json
#2
1
If you are using jQuery you can do the following
如果您使用的是jQuery,则可以执行以下操作
var data = jQuery.parseJSON('[{"name":"YHet","organism_id":"4ea9b90e859723d3f7000037"}]');
#3
0
Use eval:
var dataObject = eval('(' + dataString + ')');
var dataObject = eval('('+ dataString +')');
#4
0
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对象,或者如果使用jQuery,则使用$ .jsonParse方法尝试使用JSON对象,否则使用eval或更安全的方式解析。
#5
0
On 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
#1
8
Why don't you do:
你为什么不这样做:
data = <%= @chromosomes.html_safe %>;
Sidenote:
I hope you do something like:
我希望你做的事情如下:
@chromosomes = [{ name: "YHet", organism_id: "foo" }].to_json
#2
1
If you are using jQuery you can do the following
如果您使用的是jQuery,则可以执行以下操作
var data = jQuery.parseJSON('[{"name":"YHet","organism_id":"4ea9b90e859723d3f7000037"}]');
#3
0
Use eval:
var dataObject = eval('(' + dataString + ')');
var dataObject = eval('('+ dataString +')');
#4
0
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对象,或者如果使用jQuery,则使用$ .jsonParse方法尝试使用JSON对象,否则使用eval或更安全的方式解析。
#5
0
On 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