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
Solution 1:
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:
vardata = ["key1", "value1", "key2", "value2",...];
Or, you could do an array of objects:
vardata = [{key: "key1", data: "value1"}, {key: "key2", data: "value2"}, {...}]
Solution 2:
Keys within an object aren't technically ordered. That you expect them to be in a particular order is a mistake in data structure. A JSON parser will interpret numerical keys as array positions.
this
{
55: "foo",
29: "bar",
...
}
is semantically the same as:
object[55] = "foo"object[29] = "bar"
which is:
[
...
"bar" //index 29
...
"foo" //index 55
...
]
Instead, you should separate the order and the identify of your objects:
[
{id: 55, content: "foo"},
{id: 29, content: "bar"},
...
]
Post a Comment for "Json Object Being Reordered By Javascript"