Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to model identifiers (unique id) in JSON

Tags:

json

When modelling JSON data we have usually to deal with unique objects identifiers. We could model them as (i) key (or property) or as (ii) value. Which is the best solution, if any, or what are pros and cons? Here there is an example.

Identifier as key:

[
  {
    "1": {
      "tel": "tel1",
      "e-mail": "mail2"
    }
  },
  {
    "2": {
      "tel": "tel2",
      "e-mail": "mail2"
    }
  }
]

Identifier as value of id key:

[
  {
    "id": 1,
    "tel": "tel1",
    "e-mail": "mail2"
  },
  {
    "id": 1,
    "tel": "tel2",
    "e-mail": "mail2"
  }
]
like image 831
floatingpurr Avatar asked Sep 22 '15 12:09

floatingpurr


1 Answers

The benefit of number 2

[
  {
    "id": 1,
    "tel": "tel1",
    "e-mail": "mail2"
  },
  {
    "id": 1,
    "tel": "tel2",
    "e-mail": "mail2"
  }
]

could be that each model and it's information is represented as one JSON object. This is logical if a model's ID is a property of the model. In that case it's nice to keep all the properties housed in one object, without needing nested objects to describe properties that are on the same 'level' as far as the model is concerned.

However, for the same reason, if the ID is not a property of the model, but a seperate value, then you should go with option 1 since it says: here is the first object, and these are its properties. Here is the second object, and these are its properties, etc.

Another potential benefit of 2 is that is can be easier to parse on the client side (this depends on how you parse it, which library you use, etc., of course). If parsing manually, you could simply loop over all objects in the JSON array, and each item in that loop represents one model with all its properties, with no need to dig deeper, as you would need to with 1.

Also, as Pietro correctly suggested, option 1 can be made prettier by removing the {} around each object.

{
    "1": {
        "tel": "tel1",
        "e-mail": "mail2"
    },
    "2": {
        "tel": "tel2",
        "e-mail": "mail2"
    }
}

However, then your entire JSON would be one object. That is semantically wrong. You shouldn't do that.

Taking that into account, option 2 is also prettier. Less consfusing {}'s.

Another correct remark by Pietro:

JSON is a data-interchange format, not really close to a modeling tool. You should look first at your data model, (class, database or what else), then at your JSON (de)serializer: your choice of JSON representation should arise from there

like image 85
Tim Avatar answered Nov 15 '22 00:11

Tim