Weird JSON Javascript problem in Rails

12,266

This is Rails html-encoding your string as is default in Rails 3.

You need to mark your JSON as html_safe:

var stuff = <%= @json.to_s.html_safe %>

Note that .to_s is needed because as_json gives Hash instead of string. You could do this instead:

# in controller
@json = @nodes.to_json(:only => [:ID, :Lat, :Lon]) 

#and in view
var stuff = <%= @json.html_safe %>
Share:
12,266
readmymsg123
Author by

readmymsg123

Updated on June 25, 2022

Comments

  • readmymsg123
    readmymsg123 almost 2 years

    I'm trying to get my JSON from my controller to my view. In my controller I am doing:

    @nodes = Node.all
    @json = @nodes.as_json(:only => [:ID, :Lat, :Lon]) 
    

    In my view I have tried:

    1) var stuff = <%= @json %>
    2) var stuff = <%= @json.to_json %>
    3) var stuff = <%= @json.to_json.to_json %>
    

    and all of those give me an error. I usually get an "Unexpected Syntax Error &" or "Unexpected Syntax Error {"

    I have also tried using jquery and using respond_to within the controller, but that doesn't seem to work either.

    My thoughts are that getting json to the view shouldn't be a big issue and shouldn't require jQuery, and currently, my page source looks like:

    var stuff = [{&quot;node&quot;:{&quot;ID&quot;:1301499692582,&quot;Lat&quot;:42.3605063113369,&quot;Lon&quot;:-71.0870862191138}},{&quot;node&quot;:{&quot;ID&quot;:1301499691515,&quot;Lat&quot;:42.3605147089149,&quot;Lon&quot;:-71.0870533282532}},{&quot;node&quot;:{&quot;ID&quot;:1301431075499,&quot;Lat&quot;:42.3605456103,&quot;Lon&quot;:-71.0875239075536}} etc
    

    I dont understand the &quot symbols (maybe thats where the syntax error is coming from) but when I do render :json => @nodes.to_json, the page renders a normal json that is valid:

    [{"node":{"ID":1301499692582,"Lat":42.3605063113369,"Lon":-71.0870862191138}},{"node":{"ID":1301499691515,"Lat":42.3605147089149,"Lon":-71.0870533282532}},{"node":{"ID":1301431075499,"Lat":42.3605456103,"Lon":-71.0875239075536}}
    

    Note: I've also tried doing var stuff = '<%= @json.to_json %> but when I do var json = JSON.parse(stuff), it gives me an illegal token error.

    Can someone please help me with this? Thanks so much!