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]) 

在我看来,我try 过:

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

所有这些都给了我一个错误.我通常得"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.

我的 idea 是,将json放到视图中应该不是什么大问题,也不应该需要jQuery,目前,我的页面源代码如下所示:

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.

有人能帮我吗?非常感谢!

推荐答案

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

您需要将JSON标记为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 %>

Json相关问答推荐

如何使用Aeson解码带有Unicode字符的JSON文件?

我发现GoFr响应总是包含在数据字段中,如何返回自定义响应?

修改Deneb图表中工具提示的字体大小

Vega-Lite(Deneb):难以将最小和最大值应用于折线图和文本标签以及线条末尾的点

从Postgres表中的JSON中提取值

使用 JOLT 将日期格式转换为 JSON

如何获取 JSON 对象字段值和同一 JSON 对象的下一个数组中的字段值?

Ansible - 将文件内容添加到字典中

在 python 中循环 JSON 数组

Vega-Lite规范:尽管在规范中提供了数据,但显示空图表

将请求中的数据推送到数组中

当值包含ansible中的字符串时解析json值

避免 KeyError 的默认字典键

如何从 HttpClient 解析 JSON 字符串?

编写 JSON 日志(log)文件的格式?

如何将 LinkedHashMap 转换为自定义 java 对象?

在 Jersey 服务中使用 JSON 对象

如何在 Django JSONField 数据上聚合(最小/最大等)?

与classic 规范化表相比,postgres JSON 索引是否足够高效?

如何从 BindingResult 获取控制器中的错误文本