Nested JSON objects - do I have to use arrays for everything?

John Schulze picture John Schulze · Jan 20, 2010 · Viewed 309.1k times · Source

Is there any way to have nested objects in JSON so I don't have to make arrays out of everything? For my object to be parsed without error I seem to need a structure like this:

{"data":[{"stuff":[
    {"onetype":[
        {"id":1,"name":"John Doe"},
        {"id":2,"name":"Don Joeh"}
    ]},
    {"othertype":[
        {"id":2,"company":"ACME"}
    ]}]
},{"otherstuff":[
    {"thing":
        [[1,42],[2,2]]
    }]
}]}

If I fetch this object into a variable called "result" I have to access the nested objects like this:

result.data[0].stuff[0].onetype[0]

and

result.data[1].otherstuff[0].thing[0]

This seems clumsy and redundant to me, if possible I would prefer:

result.stuff.onetype[0]

and

result.otherstuff.thing

But how can I use the object keys directly when everything is an array? To my confused and uneducated mind something like this would seem more appropriate:

{"data":
    {"stuff":
        {"onetype":[
            {"id":1,"name": ""},
            {"id":2,"name": ""}
        ]}
        {"othertype":[
            {"id":2,"xyz": [-2,0,2],"n":"Crab Nebula","t":0,"c":0,"d":5}
        ]}
    }
    {"otherstuff":
        {"thing":
            [[1,42],[2,2]]
        }
    }
}

I've probably misunderstood something fundamental here, but I cannot get the jQuery parser (nor the native FF parser used by jQuery 1.4) to accept the second style object. If anyone can enlighten me it would be gratefully appreciated!

Answer

SLaks picture SLaks · Jan 20, 2010

You don't need to use arrays.

JSON values can be arrays, objects, or primitives (numbers or strings).

You can write JSON like this:

{ 
    "stuff": {
        "onetype": [
            {"id":1,"name":"John Doe"},
            {"id":2,"name":"Don Joeh"}
        ],
        "othertype": {"id":2,"company":"ACME"}
    }, 
    "otherstuff": {
        "thing": [[1,42],[2,2]]
     }
}

You can use it like this:

obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1]  //thing is a nested array or a 2-by-2 matrix.
                            //I'm not sure whether you intended to do that.