Search code examples
jsonapiget

json object format for user data api


I have made an API that serves user data as a json file (e.g. name, userId...). The idea is that when someone logs in, their user ID loads the user data specific to them. I am not sure if I am supposed to create 'users' as an array or as an object. An array is more elegant, but if 'users' is an object I can pick out the right 'user' object with a key-value pair, where the key is the user ID.

How do I find the right user if I use an array? Which way is proper JSON?

{
  "users": {
    "1": {
      "userId": "1",
      "displayname": "Fred"
    },
    "2": {
      "userId": "2",
      "displayname": "Ben"
    },
    "3": {
      "userId": "3",
      "displayname": "Sarah"
    }
  }
}

or

{
  "users": [
    {
      "userId": "1",
      "displayname": "Fred"
    },
    {
      "userId": "2",
      "displayname": "Ben"
    },
    {
      "userId": "3",
      "displayname": "Sarah"
    }
  ]
}

Solution

  • Always try to keep the keys in the JSON constant rather than making them dynamic. Dynamic keys are complex to parse on the client side. You can always include the info about the dynamic key also inside a object with some fixed key.