Search code examples
jsonmodeling

JSON Modelling Approaches


Imagine I am storing a person's phone numbers in JSON format. One such JSON record might look as follows:

{
  "firstName": "John",
  "lastName": "Smith",
  "phoneNumber": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "mobile",
      "number": "646 555-4567"
    }
  ]
}

One alternative structure to the above is:

{
  "firstName": "John",
  "lastName": "Smith",
  "homePhone": {
    "number": "212 555-1234"
  },
  "mobilePhone": {
    "number": "646 555-4567"
  }
}

What are the pros and cons of the two modelling approaches? The obvious one I see is that the first approach allows one to retrieve all phones in one go.


Solution

  • In order to decide what to do in this cases you should think in your implementation too.

    Let's say for example that you will be parsing and using this with Python. If you put it as a list, you will have to loop through the list in order to find a given number which in the worst case scenario might end up as an O(n) task.

    If you re-factor it to be a dictionary (hash table), looking up a phone number by accessing the right key would be closer to O(1).

    In summary, what you're doing with your data and how are you going to use it should dictate its structure.