Search code examples
ruby-on-railsjsonsyntax-errorillegal-charactersto-json

Using to_json gives me illegal character


I passed a ruby variable to javascript using the to_json method, but the console returns me an error saying "SyntaxError: illegal character" for the following line:

var home = #{@home.to_json};

Does anyone knows whats wrong?


Solution

  • If this is in a .erb file you can do the following:

    var home = <%= @home.to_json %>;
    

    Otherwise (haml or something else) you could use the parseJSON method from jQuery in combination with Ruby's string interpolation:

    var home = $.parseJSON("#{@home.to_json}");
    

    More information about the parseJSON method can be found here.