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?
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.
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.
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.
Save this question. Show activity on this post. JSON.
Use an array if you want to keep the order. That should be the only way to maintain the order in javascript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With