What is the right way to write JSON for example persondata? [closed]

Simple question, what is better? Please explain in 1-2 sentences why. I haven’t much worked with JSON files but think in future I will do more often. So it’s better to start with proper structure, instead of working some time and realize another structure would be better.

“id” as key:

    {
    "0": {
        "name": "name1",
        "bdate": "bdate1",
        "mail": "mail1",
        "sex": "sex1"
    },
    "1": {
        "name": "name2",
        "bdate": "bdate2",
        "mail": "mail2",
        "sex": "sex2"
    },
    "2": {
        "name": "name3",
        "bdate": "bdate3",
        "mail": "mail3",
        "sex": "sex3"
    }
}

“id” in data:

    [
    {
        "id":"0",
        "name": "name1",
        "bdate": "bdate1",
        "mail": "mail1",
        "sex": "sex1"
    },
    {
        "id":"1",
        "name": "name2",
        "bdate": "bdate2",
        "mail": "mail2",
        "sex": "sex2"
    },
    {
        "id":"2",
        "name": "name3",
        "bdate": "bdate3",
        "mail": "mail3",
        "sex": "sex3"
    }
]

Answer

Using an object indexed by ID will make it easier to look up objects if there will be circumstances in which you’ll have the ID to find in advance. With that, using your first approach will let you find the object as easily as:

const personObj = allObjects[id]

If you used an array instead, you’d have to iterate over the whole array in order to find it:

const personObj = allObjects.find(
  obj => obj.id === id
);

which is an order of magnitude slower (though, that’s only relevant if the amount of data is quite large).

Of course, make sure an ID uniquely identifies one, and only one, object.

If the IDs happen to exactly correspond to their position in the array – as in this example – you could use the array instead and use allObjects[id] – but that could create problems later if items ever get added or removed from the array.