简体   繁体   中英

print json object to string format

Iam trying print json object to string format.

(Actually i got these data value from ruby code var data = '<%=[@pro {|c| {x:cx, y:cy}}].to_json%>' )

while printing the data variable i got values containing &quot instead of '

var data=[[{&quot;x&quot;:1,&quot;y&quot;:0}]]

I want to get the values in the format var data="[[{ 'x': '1', 'y': '0' }]]";

while removing &quot; using the code var dataset=JSON.parse(data.replace(/&quot;/g,'"')); got in the following format.

var dataset =[[{"x":1,"y":0}]]

i want to print the values like [[{ 'x': '1', 'y': '0' }]] .How it is possible.

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.

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:

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.

var dataset =[[{"x":1,"y":0}]]
var JsonData = JSON.stringify(dataset);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM