Javascript Rails JSON Problem
I have a large json from my rails controller:
@json = {:Nodes => @nodes.as_json(:only => [:ID, :Lat, :Lon])}
and I want to use it in my javascript in my views. In a larger scope, I want to use the json to retrieve lat and lon's to plot on a Google Map. However, right now, I'm just trying to see if I can get all the points properly. My question is:
What's a good way to parse the json in the javascript file? (Note: the file's extension is still html.erb) I've tried:
var stuff = eval('(' + <%= @json %> + ')');
but that doesn't seem to be working. Can anyone help? Thanks开发者_C百科 so much!
Since JSON is actually all legal javascript syntax, I frequently do this:
var stuff = <%= @json_hash.to_json %>;
Simplest thing that could possibly work. If you are getting your JSON from an untrusted source, it's better to use a library function to parse it, which will prevent it from executing code. Also, be sure to call to_json
on your final hash. You don't want to just to_s
it, which is the default in erb
.
@json = {:Nodes => @nodes.map({|n| [n[:ID], n[:Lat], n[:Lon]] })}.to_json
using prototype you could do this:
var stuff = '<%= raw @json %>'.evalJSON();
or using jquery:
var stuff = jQuery.parseJSON('<%= raw @json %>');
In Rails 4 all this solutions not work for me, so i make this:
var consumers;
consumers = <%= @consumers.to_json.html_safe %>;
So consumers[0]
generate Object
(model Rails), you can iterate to transform in your objects like:
function consumersRubyToJavascriptArray(json){
for (var i = 0; i< json.length; i++) {
consumers.push(new Consumer({ id: json[i][0], name: json[i][2], phone: json[i][3], cpf: json[i][4]}));
}
}
精彩评论