我希望在 Rails 中返回 json 请求的一些数据,我想知道返回的数据是否格式错误。这是一个简短的示例:
[{"company":{"name":"A"}},{"company":{"name":"B"}}]
我一直认为返回 json 时它应该描述根元素和复数,因此它应该返回更像是的内容:
{"companies":[{"name":"A"},{"name":"B"}]}
以下是问题 - 有什么方法可以让我的 json 以这种格式输出?这是否是正确的格式,或者每个公司节点是否也需要标记?我是否必须创建自定义视图才能获取结果?让 jQuery 以当前格式循环数据的最佳方法是什么?现在我正在使用:
format.json { render :json => @companies.to_json() }
渲染结果。
预先感谢您的任何帮助/建议。
I'm looking to return some data for a json request in rails and I was wondering if the data being returned is malformed. Here is a shortened example:
[{"company":{"name":"A"}},{"company":{"name":"B"}}]
I always thought that when returning json it should describe the root element and plurals, so it should return something more like:
{"companies":[{"name":"A"},{"name":"B"}]}
Here are the questions - Is there any way I can get my json to come out in that format? Is that even the correct format or does each company node need to be labeled as well? Do I have to create a custom view to get my results? What is the best way to get jQuery to loop the data in the current format? Right now I'm using:
format.json { render :json => @companies.to_json() }
To render the results.
Thanks in advance for any help/advice.
发布评论
评论(2)
您可能正在寻找类似于 JSend 规范 的内容。在我意识到以前已经这样做过之前,我自己就想到了这个,因为我发现为 JSON 服务提供一个标准响应容器非常有用。
以下是我重写服务器响应的方法:
有时您需要更改转换为
JSON
时生成的属性。在这些情况下,我只使用map
:比
to_json
更详细一点,但它更灵活,并且在 Rack 中间件中工作得同样好。You're probably looking for something like the JSend specification. I came up with this myself before I realized it had been done before, because I've found it tremendously useful to have a standard response container for JSON services.
Here's how I would rewrite your server response:
There are times when you need to alter the attributes that are generated when converted to
JSON
. In these cases, I just usemap
:A little more verbose than
to_json
, but it's more flexible and works just as well in Rack middleware.两者都是有效的 JSON。不过,我同意你的观点,第二种更好。它的冗余度较低,因为第一个有不必要的对象层并重复公司密钥。但更微妙的好处是,第二个可以保护您免受 JSON 劫持,只有当根结构是数组时才可能。
要循环第一个,请使用例如
Both are valid JSON. However, I would agree with you that the second is preferable. It's less redundant, since the first has an unnecessary object layer and repeats the company key. But a more subtle benefit is that the second protects you from JSON hijacking, which is only possible when the root structure is an array.
To loop the first, use e.g.