Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which format is better for list in JSON API design, flat array or nested object?

For list API, such as Users, I find that there are two common formats. Arrays:

// flat array
[
  {
    "login": "octocat",
    "id": 1
    ...
  },
  ...
]

GitHub, Heroku and Twitter use this format

VS Objects:

{
  "results": [
    {
      "login": "octocat",
      "id": 1
      ...
    },
    ...
  ]
}

Parse and Slack and instagram use this format.

Which one is better? How to compare these two formats?

like image 490
Tony Han Avatar asked Mar 26 '26 12:03

Tony Han


1 Answers

Array-oriented data has the following advantages:

  • Client-side JavaScript has more methods for arrays than objects
  • No need for root node to simulate a tree structure for a tabular structure

and disadvantages:

  • No namespacing since indexes are numeric
  • JSON.parse fails in client-side JavaScript

Key/Value-oriented data has the following advantages:

  • JSON.parse works in client-side JavaScript
  • Namespacing makes duplicate values easier to disambiguate
  • JSON.stringify works to make simple transformations easier compared to array methods

and disadvantages:

  • It can be hard to iterate nested hierarchies without a library in client-side code
  • JSON.parse in client-side code removes duplicate key names on the same level

References

  • Want to return and array from the Restful Web services?
  • Read local file text (tab separated values) with d3 or ajax cause syntax error in firefox development console
  • Query JSON/XML/CSV using SQL | Joe Conley
like image 133
Paul Sweatte Avatar answered Mar 29 '26 09:03

Paul Sweatte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!