[英]print json object to string format
Iam trying print json object to string format. 我正在尝试将json对象打印为字符串格式。
(Actually i got these data value from ruby code var data = '<%=[@pro {|c| {x:cx, y:cy}}].to_json%>'
) (实际上,我是从ruby代码中获取这些数据值的var data = '<%=[@pro {|c| {x:cx, y:cy}}].to_json%>'
))
while printing the data variable i got values containing "
instead of '
在打印数据变量时,我得到的值包含"
而不是'
var data=[[{"x":1,"y":0}]]
I want to get the values in the format var data="[[{ 'x': '1', 'y': '0' }]]";
我想获取格式为var data="[[{ 'x': '1', 'y': '0' }]]";
while removing "
同时删除"
using the code var dataset=JSON.parse(data.replace(/"/g,'"'));
got in the following format. 使用代码var dataset=JSON.parse(data.replace(/"/g,'"'));
获得以下格式。
var dataset =[[{"x":1,"y":0}]] var数据集= [[{“ x”:1,“ y”:0}]]
i want to print the values like [[{ 'x': '1', 'y': '0' }]]
.How it is possible. 我想打印类似[[{ 'x': '1', 'y': '0' }]]
值。
If you are using only 2 variables, than you can simple do like that: 如果仅使用两个变量,则可以简单地执行以下操作:
var data = [[{'x': '<%= @pro.x %>', 'y': '<%= @pro.y %>'}]];
And no need to use to_json
method. 无需使用to_json
方法。
If you are want to stringify many values than this code works like a charm: 如果您想对许多值进行字符串化处理,则此代码就像一个超级魅力:
<% array = [[{'x' => 1, 'y' => 1}], [{'x' => 2, 'y' => 2}], [{'x' => 3, 'y' => 3}]] %>
<%= array.to_json %>
And he outputs: 他输出:
[[{"x":1,"y":1}],[{"x":2,"y":2}],[{"x":3,"y":3}]]
If you need to send json by request in your controller use: 如果您需要通过控制器中的请求发送json,请使用:
def send_json_array
array = [[{'x' => 1, 'y' => 1}], [{'x' => 2, 'y' => 2}], [{'x' => 3, 'y' => 3}]]
response.headers['Content-type'] = "text/plain; charset=utf-8"
render :text => array.to_json
end
JSON.stringify converts an object to its json format. JSON.stringify将对象转换为其json格式。
var dataset =[[{"x":1,"y":0}]]
var JsonData = JSON.stringify(dataset);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.