2

I'm trying to access a nested json array

        var jsonResponse:Object = JSON.decode(response);
        var foo:Object = JSON.decode(jsonResponse.nested);
        var bar:Array = foo as Array;

When i inspect foo - its an object with about 50 children objects.

I can read the properties of the children objects.

However, when i cast foo as an Array it comes back null.

I'd prefer to not iterate over each object and push it into an array.

Any advice?

Jack Murphy
  • 2,952
  • 1
  • 30
  • 49
  • I don't think you should call JSON.decode twice. The first call will parse the JSON string into an object, and from then on you can use jsonRespons and its properties without further decoding. For example, jsonRespons.nested may be an array, no need to decode it. – Lars Blåsjö Aug 19 '11 at 00:22

2 Answers2

3

If you have an object, you indeed cannot cast it to an Array. You either need to modify the JSON string (if you have access to it), or iterate over the properties as an object:

for (var n:String in foo) {
    var value = foo[n];
    trace(value);
}

Or if you really want to use an array, you need to create it manually:

var bar:Array = [];
for (var n:String in foo) {
    var value = foo[n];
    bar.push(value);
}
laurent
  • 88,262
  • 77
  • 290
  • 428
3

You could decode the JSON right into an Array instead of Object, like this:

var jsonResponse:Array = JSON.decode(response);
var foo:Array = JSON.decode(jsonResponse.nested);

Have a look at this question: AS3 JSON parsing

Community
  • 1
  • 1
Mentoliptus
  • 2,855
  • 3
  • 27
  • 35