0

I am able to pull JSON data from PHP into my Flex application just fine with the following bit of code:

public function httpResult(event:ResultEvent):void { 
    var rawData:String = String(event.result);
    trace(String(event.result)); //shows correct order
    var as3Data:Object = JSON.decode(rawData);

    for (var i:* in as3Data)  {
        trace(i + ": " + as3Data[i].unit_price); //shows incorrect order
    }
}

When I trace the result, I see the information I am pulling in the correct order.

{"100":{"unit_price":"2.9567"},"400":{"unit_price":"1.0991"},"800":{"unit_price":"0.7926"},"1200":{"unit_price":"0.6911"}} {

But, once I JSON.decode the result, somehow it re-orders the content. And, puts the first item last.

400: 1.0991, 800: 0.7926, 1200: 0.6911, 100: 2.9567

Does anyone have any ideas on why it would be doing this? Or ideas on how I can re-order the Object myself?

0

2 Answers 2

1

Objects in AS3 aren't ordered. JSON key-value pairs obviously do have an ordering (it's in the text!), but I don't think there's any guarantee it'll be kept when the JSON is either encoded or decoded.

If you've got specific ordering requirements, you should probably create a list with objects in it:

[
    {"100":{"unit_price":"2.9567"}},
    {"400":{"unit_price":"1.0991"}},
    {"800":{"unit_price":"0.7926"}},
    {"1200":{"unit_price":"0.6911"}}
]
Sign up to request clarification or add additional context in comments.

Comments

0

For the most part Andrew's answer is right on, because yeah objects in AS3 aren't ordered. However I wouldn't create a list of objects; rather I would create a list of keys used to index into the JSON object. That way it's easy to sort the list of keys.

The code for what I'm getting at is something like:

var as3Data:Object = JSON.decode(rawData);
var keys:Array = [];

for (var i:* in as3Data)  {
  keys.push(i);
}

keys.sort();  //don't know the correct sort off the top of my head, sorry

for (var key:* in keys) {
  trace(key + ":" + as3Data[key].unit_price);
}

1 Comment

This is what I was going to do, but I was looking for the sort method. For each key call rawData.indexOf(key), that will give you something to use to sort.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.