How to maintain order when parsing JSON from Javascript?

Go To StackoverFlow.com

12

The data I am sending my page is encoded in JSON, parsed using Javascript then displayed in an HTML SELECT element using a loop. The data arrives already sorted, but I am having issues keeping the correct order when decoding the JSON string, which nullifies the sorting applied on the data.

Sample data: {"test":{"4":"first","5":"second","3":"third"}}

Using jQuery's JSON parser and Javascript's eval() function, I am getting the following results:

{"test":{"3":"third","4":"first","5":"second"}}

It is not possible to modify the format of the data and the keys ("4", "5", "3") must remain in the same order. The real data is much more complex, but this sample illustrates very well my issue.

How can I maintain the order of the JSON data when parsing it from Javascript?

2012-04-05 19:17
by Wolf
When you are using properties (object literal) you should not depend on the order. Only arrays (both in JavaScript and in JSON) preserve order - Tomasz Nurkiewicz 2012-04-05 19:20
What bothers me is that the custom JSON parser on http://json.parser.online.fr/ is working just fine. Sadly, I can not modify the format of the data or I would be using arrays. : - Wolf 2012-04-05 19:21
You should complain to whomever made this data that they did a terrible job of designing the JSON representation. If order is important an Object should not be used - Phrogz 2012-04-05 19:25
@Phrogz Already done, but it's not going to change much. I'd have to change about 35% of the application to fix this issue. I might decide to just live with it and do extra sorting afterwards. This is nothing compared to other atrocities I have seen in this code.. - Wolf 2012-04-05 19:28


11

Use an array if you want to keep the order. That should be the only way to maintain the order in javascript.

2012-04-05 19:19
by CD..
It is not possible to modify the format of the data, sadly. : - Wolf 2012-04-05 19:20
@Wolf Then you'll need to hand-parse it yourself, keeping an array in addition to the data that stores the order of the properties. JavaScript simply does not guarantee the iteration order of properties on an object - Phrogz 2012-04-05 19:21
@Phrogz I was hoping for a ready-made solution, but I guess home-made will have to be the way to go. I'll give this question some time, maybe someone will come up with something - Wolf 2012-04-05 19:23
@Wolf I suspect it would be a rather trivial modification to a JSON parser to keep track of the keys in an array as they are seen. (Perhaps right about at this line. - Phrogz 2012-04-05 19:28
Sadly, it really is the only way to maintain order. Either I need to modify the data to use an array or implement the sorting function in the Javascript code - Wolf 2012-04-05 19:45
This really isn't an answer. Technically speaking, JSON objects are unsorted, but many people want to preserve their current order - Steve Bennett 2016-09-15 10:10
Ads