I have done a fair amount of work with JSON in the past, but I've never needed to write my own JSON object. Now that I'm tasked with doing so, I'm having some trouble creating it in such a way that will cause me the least amount of trouble down the road. Basically, I want to do it right the first time.
My JSON array will eventually grow larger, but for these purposes I'll keep it small.
Here is what I have currently done:
{
"ClassGroup": [
{
"id": "123",
"classname": "Class 1",
"isActive": "true",
"isExpanded": "false",
"students": [11, 22, 33, 44, 55],
"isSelected": [11, 22, 33, 44, 55]
},
{
"id": "456",
"classname": "Class 2",
"isActive": "false",
"isExpanded": "false",
"students": [66, 77, 88, 99],
"isSelected": [66, 88, 99]
}
],
"Student": [
{
"id": "11",
"first": "Student",
"last": "One",
"classes": [123],
"isSelected": [123]
},
{
"id": "22",
"first": "Student",
"last": "Two",
"classes": [123],
"isSelected": [123]
}
]
}
A lot of the students and classes are missing from the array for now, so ignore any missing IDs that you see.
When doing it this way, and running the jQuery.getJSON function, I end up with an array like this:
data['ClassGroup'][0]['id'] will equal "123" data['ClassGroup'][1]['id'] will equal "456" data['Student'][0]['id'] will equal "11"
The problem with this is that when given an ID of a class, I can't easily locate the class. For example, if I want to find the name of class "456", I would have to iterate through the array until I find the X such that data['ClassGroup'][X]['id'] will equal "456", rather than just doing data['ClassGroup']['456']['classname'].
What I would like to do is re-write this JSON such that the result of $.getJSON will be consistent with the following:
data['ClassGroup']['123']['classname'] = "Class 1" data['ClassGroup']['456']['classname'] = "Class 2" data['Student']['11']['last'] = "One"
I think you get the picture.
Am I going about this the right way?