0

I have an object like this: { "01":"111","02":"222","11":"AAA","12":"BBB"}. But after JSON.parse, the object changed its order like {"11":"AAA","12":"BBB","01":"111","02":"222"}. See http://jsfiddle.net/stxh/3WV8Y/

Code:

var str=JSON.parse('{"01":"111","02":"222","11":"AAA","12":"BBB"}');
alert( JSON.stringify(str) );

Can I keep the order from JSON.parse?

StXh
  • 1,856
  • 1
  • 13
  • 16
  • 2
    This isn't a JSON problem, but a "problem" with Javascript objects: [How to keep an Javascript object/array ordered while also maintaining key lookups?](http://stackoverflow.com/questions/5773950/how-to-keep-an-javascript-object-array-ordered-while-also-maintaining-key-lookup) – CodingIntrigue May 08 '14 at 07:39
  • @RGraham Which is consequentially a JSON problem (as JSON explicitly *does not imply order* of keys in a JSON Object). – user2864740 May 08 '14 at 07:44
  • tldr; if you need arbitrary order, use a JSON Array. If you just want to order by key value, then order and iterate by key value. – user2864740 May 08 '14 at 07:47
  • @user2864740 Heh, depends which way you look at it I suppose! – CodingIntrigue May 08 '14 at 07:51
  • 1
    @RGraham True, I like to push the issue as I've seen some undefined behavior (in code that later breaks) based on assumptions of JSON/dictionary ordering :( – user2864740 May 08 '14 at 07:53

0 Answers0