views:

136

answers:

3

i'm trying to parse json in as3 that has multiple arrays like this:

    {
    "a1": [
        {
            "a": 1,
            "b": "2",
            "c": 3 
        },
        {
            "a": 1,
            "b": "2",
            "c": 3 
        } 
    ],
    "a2": [
        {
            "a": 1,
            "b": "2",
            "c": 3 
        },
        {
            "a": 1,
            "b": "2",
            "c": 3 
        } 
    ],
    "a3": [
        {
            "a": 1,
            "b": "2",
            "c": 3 
        },
        {
            "a": 1,
            "b": "2",
            "c": 3 
        } 
    ] 
}

i don't really know hot to iterate through it to get the values out of each array though. i assume i'd use a for loop and append it to the end of the array name "a", but i'm not sure how to write this (if that's even the right way to approach it).

+2  A: 

What you have is not simply arrays, but a mixture of dictionaries (also known as hashes or associative arrays), as well as lists (arrays).

To iterate both the dictionaries and lists you can use a for each loop:

(assuming your dictionary is called data)

// loop parent dictionary
for each (var parent:Object in data)
{
    trace(parent);

    // loop child array
    for each (var child:Object in parent)
    {
        trace(child);

        // loop grandchild dictioanry
        for each (var grandchild:Object in child)
        {
            trace(grandchild);
        }
    }
}

Please bear in mind that this code is untested and you may need to cast the Object types to more specific types such as (Array)Object in order to properly iterate them.

Soviut
thanks for the description. this was very informative.
dBrek
A: 

you could iterate through the JSON like this:

for (var parent:Object in json)
{
     for (var child:Object in json[parent] )
     {
          trace(json[parent][child].a);
          trace(json[parent][child].b);
          trace(json[parent][child].c);

     }

}

you can use "parent" and "child" as keys to parse out the values

minimalpop
why not use for each since that will iterate over values rather than keys.
Soviut
thanks. i tried this format and it works beautifully.
dBrek
@Soviut, i actually wasn't aware of that. i tested out this code and it worked. however i'm curious, is using "for each" better suited for this scenario?
minimalpop
+1  A: 

Why reinvent the wheel. There are a ton of JSON libraries out there.

This article may help: Mike Chambers - Using JSON with Flex 2 and ActionScript 3

TandemAdam