Logo Questions Linux Laravel Mysql Ubuntu Git Menu

JSON object being reordered by Javascript

I have a rather large JSON object being generated via PHP. It creates a PHP object out of a database, with keys that are integers, ie 1-100. These keys are not in that order though, they are in a random order, such as 55, 72, 5, 8, 14, 32, 64, etc. I then use json_encode to output the object as JSON. I then use an AJAX call to grab that JSON and store it in a variable. However, that variable has the JSON object in order 1-100, instead of the sorted order above.

Any ideas why it's doing that, and how I can fix it?

like image 351
sharf Avatar asked Mar 19 '23 11:03


1 Answers

JSON objects have no specific order and are not guaranteed to keep the order you put things in. If you want keys in an order, you should put them in an array which will maintain order. If you want an ordered set of key/value pairs, you can use several different forms.

The simplest would be to just have a single array that is an alternating set of key, value:

var data = ["key1", "value1", "key2", "value2",...]; 

Or, you could do an array of objects:

var data = [{key: "key1", data: "value1"}, {key: "key2", data: "value2"}, {...}]
like image 52
jfriend00 Avatar answered Mar 23 '23 19:03