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 = [{"lat":37.869005...707408,"lng":-122.2545767}]
How can I set the variable successfully?
the Tin Man
161k44 gold badges222 silver badges308 bronze badges
asked Dec 2, 2012 at 20:56
Jonathan
1,4695 gold badges13 silver badges22 bronze badges
2 Answers 2
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,
answered Dec 2, 2012 at 20:58
lostsource
22k9 gold badges71 silver badges90 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Jonathan
Huh? Well, that's why I put <%= ... %> to make it recognizable to JS. Or do you mean something else?
tokland
@JonathanChen: is
@json a string or a hash?Jonathan
@tokland: I believe it is a hash.
tokland
@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.Assuming @json is a Ruby object:
<%= javascript_tag do %>
var test = <%= @json.to_json.html_safe %>;
<% end %>
answered Dec 2, 2012 at 21:26
tokland
68.2k13 gold badges151 silver badges174 bronze badges
1 Comment
kbridge4096
Yes,
.to_json is necessary here.default
<%= raw @json =>