0

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 so much!

4
  • I used firebug, and it says that there's an unexpected token of : but isn't that supposed to be a part of JSOn anyways? Commented May 11, 2011 at 3:38
  • Could you please post the relevant parts of your controller, html, and js files? Commented May 11, 2011 at 4:28
  • Sure Behrang! My controller function looks as follows: def map @nodes = Node.all @json = {"Nodes" => @nodes.as_json(:only => [:ID, :Lat, :Lon])} end and my html file simply looks like this: <!DOCTYPE html> <html> <head> <script type="text/javascript"> var stuff = <%= @json %>; var json = JSON.parse(stuff); alert("text"); </script> </body> </html> Any ideas? The Node class simply contains nodes with ID Lat and Lon along with other information that I don't include using the :include symbol Commented May 11, 2011 at 5:36
  • Could you edit your post to include your controller and view source? (by the by, I believe you can use back tick to pre within a comment) Commented May 26, 2011 at 22:52

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

9 Comments

So I call the to_json method even though I called the as_json method in the controller? I tried that and it gave me an unexpected token { error. I'm so confused. If you could give me more help, that would be great!
I've also checked JSLint to make sure my JSON is valid and tried JSONParse ... what is wrong!?! =(
I believe as_json just returns a hash that is suitable for calling to_json on. You can try it in rails console to see what it's doing. I don't understand what you're saying about JSLint. If you have a valid JSON string, just drop it in the document after a var declaration.
Hi Austin, sorry about the confusion. I just rendered my json and put it into JSONlint which checks if its valid, and it checks out, so that's why I'm confused as to why it doesn't validly parse in the javascript. Any ideas?
Can you post some representation of the JSON output, and the exact error message you are receiving?
|
1
@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 %>');

Comments

0

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]}));
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.