JSON Modeling

Imagine that I’m storing a person’s phone numbers in JSON format. One such JSON entry might look like this:

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

One alternative structure above:

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

What are the pros and cons of the two modeling approaches? Obviously, I see that the first approach allows you to get all the phones in one go.

+4
source share
2 answers

To decide what to do in this case, you should also think about your implementation.

Say, for example, that you will understand and use this with Python. If you put it in a list, you have to iterate over the list to find a given number, which in the worst case could end up as an O (n) task.

If you refactor it as a dictionary (hash table), finding the phone number by accessing the right key will be closer to O (1).

In general, what you do with your data and how you intend to use it should dictate its structure.

+2
source

I think your first example is better.

With your first solution phone number is just a collection, and it is easy to add / delete / filter a phone number.

 // ES6 const allMobilePhones = user.phones.filter(phone => phone.type === 'mobile'); // With Lodash/Underscore var allMobilePhones = _(user.phones).filter(function(phone){ return phone === 'mobile'; }); 

It is also more readable for documentation, you do not need to talk about attributes mobilePhone , homePhone , unusedPhone , workPhone . Another thing, if you add a new phone type, you don't care that you just need to add a new type value.

If you are working on exposing JSON by API, look: micro-api or json-api .

+1
source

All Articles