0

I have a Ruby variable:

@json = [{"lat":37.8690058,"lng":-122.2555342},{"lat":37.8739362,"lng":-122.2653001},{"lat":37.8701101,"lng":-122.2578559}]

When I try:

<script type="text/javascript" charset="utf-8">

   var test = <%= @json %>
   console.log(test);

</script>

Firebug tells me:

invalid property id
var test = [{&quot;lat&quot;:37.869005...707408,&quot;lng&quot;:-122.2545767}]

How can I set the variable successfully?

1
  • As you can see, Rails escapes output unless you tell it not to. Try <%= raw @json => Commented Dec 2, 2012 at 21:08

2 Answers 2

3

Seems like your JSON quotes are being replaced with HTML entities. Try using .html_safe

var test = <%= @json.html_safe %> 

If that doesn't solve it have a look in this other post as I'm no ruby expert,

Don't escape html in ruby on rails

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

4 Comments

Huh? Well, that's why I put <%= ... %> to make it recognizable to JS. Or do you mean something else?
@JonathanChen: is @json a string or a hash?
@tokland: I believe it is a hash.
@JonathanChen: you believe? is your code! :-) anyway, {"key": value} is not a Ruby Hash. :key => value} or key: value}` are. Check my answer, if @json a Ruby hash, you need to_json.
1

Assuming @json is a Ruby object:

<%= javascript_tag do %>
  var test = <%= @json.to_json.html_safe %>;
<% end %>

1 Comment

Yes, .to_json is necessary here.

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.