admin管理员组文章数量:1278985
When using MongoDB with Mongoskin in a Node.js webb app I can run .find()
on a collection to fetch all its document. The result is a mongodb cursor.
This cursor is then converted to an Array with the cursors .toArray()
method.
[
{
_id: "53ea101656cb0c0407306405",
key: "value",
...
},
{
_id: "53ea101656cb0c0407306405",
key: "value",
...
},
...
]
But is this a valid JSON output for a REST Api?... or should i convert the outer array to an object? Maybe it doesn't matter?
When using MongoDB with Mongoskin in a Node.js webb app I can run .find()
on a collection to fetch all its document. The result is a mongodb cursor.
This cursor is then converted to an Array with the cursors .toArray()
method.
[
{
_id: "53ea101656cb0c0407306405",
key: "value",
...
},
{
_id: "53ea101656cb0c0407306405",
key: "value",
...
},
...
]
But is this a valid JSON output for a REST Api?... or should i convert the outer array to an object? Maybe it doesn't matter?
Share Improve this question asked Aug 12, 2014 at 13:07 Anders ÖstmanAnders Östman 3,8326 gold badges29 silver badges50 bronze badges3 Answers
Reset to default 10It is valid JSON, assuming you put quotes around your keys. REST does not specify the format that a JSON response must use, so do whatever is right for your application.
As others have said, this violates no rules of any kind, and is totally fine.
However, at the risk of overplicating the situation, I would caution that if you wish to add meta-data to the response about this collection, you might want to wrap the array in an object. For example, if you'd like to put some hypermedia links in the response body relating specifically to this collection (for self, or creation of new objects, or paging perhaps), it is unlikely that they would fit anywhere inside the array. You could put the links in the header, of course, that is up to you.
But in general, you may want to put some meta-data in the response body, so keep that in mind and make sure you try to future-proof this response as much as is reasonably possible.
Arrays are fine and are often preferred when fetching a collection. Most JS REST libs (like Backbone) will work out of the box when an array is returned for a collection GET and would require a bit of extra code in order to extract the array.
本文标签: javascriptIs an outer array valid JSON for a REST apiStack Overflow
版权声明:本文标题:javascript - Is an outer array valid JSON for a REST api? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741302175a2371152.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论