1

Someone please help with this!!!

I'm trying to simply parse my json object in javascript within rails, and NOTHING seems to work.

The story is in the controller is:

def map 
    @nodes = Node.all
    @json = {"Nodes" => @nodes.as_json(:only => [:ID, :Lat, :Lon])}
end

In my view, I have simple javascript:

<script type="text/javascript">
var stuff = <%= @json %>;
var json = JSON.parse(stuff);
alert("text");
</script>

I'm just trying to see if the code runs through the first two lines with alert message, but it never works, always throwing me a unexpected token error (usually a colon or a { ). I've also tried doing the eval method, but that also doesn't work. Can someone please help me parse the json in the javascript? I would be eternally grateful....

2 Answers 2

1

you can go with your current approach, there are few correction that you need to make it work

@json is not a json here, its a hash and when you assign it to javascript variable it looks like

stuff = {"Nodes" => node value} here => is not accepted in javascript, thus its not a valid json object.

you need to convert hash object in json like

var stuff = <%= @json.to_json %>;
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Naren, I tried that in my code, and it gives me an unexpected token error if I try to inspect the element in Google Chrome. Any ideas on what's going on?
0

Check this out http://guides.rubyonrails.org/layouts_and_rendering.html The rendering json section.

render :json => @nodes

1 Comment

How does render pass the json to the view? I though I just need an instance variable and I can simply access that from the view?

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.