简体   繁体   中英

(AS3) Deterministic JSON String from an object?

var obj:Object = {a:"foo", b:"bar", c:"baz", d:"qux"};
trace(JSON.stringify(obj));

What determines what order the values of this object get added to the JSON string?

I need the JSON to always be the exact same, so I can't have them being in a different order which they seem to be across different clients.

Context: I'm hashing the JSON string, and comparing the hashes on a server to determine if a client is desynced.

You can't rely on JSON object keys to be in any order. If you want to create a consistent hash you need to sort the keys into an array and hash that:

var fields:Array = [];
for (var key:String in obj) {
  fields.push({key: key, value: obj[key]});
}
fields.sortOn("key");
hash(fields);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM