Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain order when parsing JSON from Javascript?

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?

like image 441
Signal Avatar asked Apr 05 '12 19:04

Signal


People also ask

Does JSON object maintain order?

The JSON standard defines objects as "an unordered collection of zero or more name/value pairs". As such, an implementation does not need to preserve any specific order of object keys.

Does JSON parse keep order?

Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine): An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

How do I make JSON ordered?

In this example you will know how to order json elements as you desire. By default the json elements will be placed in random order. By using @JsonPropertyOrder annotation, you can get the json in your desired order. The below class gives you an example on how to use @JsonPropertyOrder annotation.

Does JSON Stringify preserve order?

Save this question. Show activity on this post. JSON.


1 Answers

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

like image 69
CD.. Avatar answered Nov 15 '22 14:11

CD..