将部分渲染为 json 在换行符上返回语法错误
我有一个 json 对象,它是根据多个数据库查询的结果创建的。
我正在尝试将 json 移动到部分,以便我可以从多种方法(索引、搜索)使用相同的 json 格式。
我的结果位于 _listResults.js.erb 中,现在已将它们移至 results.json.erb 中,在 _listResults.js.erb 中,
[ <% @results.each_with_index do |result, idx| %> <%= render 'results.json.erb', result => result %> <% end %> ]
我的部分结果如下所示
{"result":<%= result.id %> ,"title":"<%= result.title %> .....
由于换行符,
... syntax error, unexpected ',', expecting keyword_end...);@output_buffer.safe_concat(',"title":');@output_buffer.a...
,我收到一条错误消息:虽然我可以将整个 json 输出放入一行,并且看起来这可以解决问题,但如果我想稍后更改输出,那么维护起来确实很痛苦。
处理这种事情最好的方法是什么。
如果这很重要的话我在Windows上(希望不会)。
谢谢
I have a json object which is created from results from multiple database queries.
I am trying to move the json into a partial so I can use the same json format from multiple methods (index, search).
I had my results in _listResults.js.erb, and have now moved them into results.json.erb and in _listResults.js.erb I have
[ <% @results.each_with_index do |result, idx| %> <%= render 'results.json.erb', result => result %> <% end %> ]
my partial looks like this
{"result":<%= result.id %> ,"title":"<%= result.title %> .....
due to the line breaks, I'm getting an error that says
... syntax error, unexpected ',', expecting keyword_end...);@output_buffer.safe_concat(',"title":');@output_buffer.a...
Though I could put the entire json output into one line, and it looks like that would resolve the problem, that would really be a pain to maintain if I want to change the output at a later time.
What's the best way to deal with this sort of thing.
I'm on Windows if that matters (hopefully it won't).
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
怎么样:
仅供参考,http://www.jsonlint.com/ 是一个很棒的网站,您可以在其中检查是否或你的 json 不是有效的。
What about:
FYI, http://www.jsonlint.com/ is great site where you can check whether or not your json is valid.
问题不在于 json,而在于 ruby 解析器的工作方式,在这种情况下,它需要在同一行上有逗号。
将你的 erb 更改为
The problem was not with the json but with the way the ruby parser works, in this case it needs to have the comma on the same line.
change your erb to
您的原始 erb 文件中有语法错误,
result =>;结果
应该是:result =>结果
。You have a syntax error in your original erb file,
result => result
should be:result => result
.