views:

959

answers:

2

I have a bit of a dilemma. I have a JSON object that has a format I'm unfamiliar with (starts with an array [] instead of an object{}) and was wondering how I might parse it in AS3. The object looks like:

[
    {
        "food": [
            {
                "name": "pasta",
                "price": 14.50,
                "quantity": 20
            },
            {
                "name": "soup",
                "price": 6.50,
                "quantity": 4
            }
        ]
    },
    {
        "food": [
            {
                "name": "salad",
                "price": 2.50,
                "quantity": 3
            },
            {
                "name": "pizza",
                "price": 4.50,
                "quantity": 2
            }
        ]
    }
]

I don't really know how I get to each food array, and each object within it. Any help would be greatly appreciated! Thanks!

+2  A: 

You will need to use the JSON Object Class (below link) http://code.google.com/p/as3corelib/

and then something like this..

var data:String = "{\"name\":\"pizza\",\"price\":\"4.50\",\"quantity\",\"2\"}";
var food:JSONObject = new JSONObject(data);
trace(food.name); // Pizza
trace(food.price); // 4.50
trace(food.quantity); // 2
food.number++;
var newData:String = String(food);
trace(newData); // {"name":"pizza","price":"4.50","quantity":"2"}
medoix
i've tried using that method, however with the json i posted above, do i need to start with a JSONArray first, and then a JSON object? since it is wrapped first by [] and then by {}.
dtrainer45
+1 AS3corelib is good. @dtrainer45: if you use adobe flexbuilder, add a breakpoint after deserializing the json string. Then you can explore the structure of the created object graph. If it is an array, it should probably be something like var x:JSONObject = new JSONObject(data); trace(x[0].food[0].name); not tested though.
Max
+1  A: 

Interesting datastructure... this should do it:

var foods:Array = JSON.decode(jsonstring);
for(var i:int = 0; i < foods.length; i++) {
  for(var j:int = 0; j < foods[i].length; j++) {
    trace(foods[i][j].name);
  }
}
Les