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 badges
Add a ment  | 

3 Answers 3

Reset to default 10

It 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