Reputation: 913
I want to understand the reason and/or core-logic for JSONObject is being an un-ordered set. Because in most of my cases there would be a request which needs response as a JSONObject in the order of time/position. After searching, I found lot of members telling to use JSONArray which I do not feel a good solution.
I want to get a clear idea before proceeding further.
Thank you in advance.
Upvotes: 0
Views: 625
Reputation: 1075059
JSONObject
represents an object defined by JSON, and JSON's object notation is unordered, by specification:
An object is an unordered set of name/value pairs.
(my emphasis)
That's because JSON was derived from (is a subset of) JavaScript's object initializer syntax in the early 2000's, and at that time JavaScript objects were unordered. (That's changed since, but using the order of JavaScript objects isn't usually a good idea, and JSON remains unordered.)
Upvotes: 2
Reputation: 200206
If JavaScript prescribed ordering of object properties, it would preclude the usage of hashtables in their implementation. On the other hand, why would an object's properties be ordered in the first place? It seems like an arbitrary constraint with, as we can see, far-reaching negative consequences.
Upvotes: 0
Reputation: 156552
The true, complete reason is only known by the members of the ECMA committee which finalized the ECMAScript specification since JSONObjects are a subset of JavaScript Objects; however, here is my guess.
To require that the properties of a JSON Object maintain a fixed order would likely add additional implementation overhead to a data structure which would otherwise be simpler without having that requirement. For example, a JSON object could be implemented as a simple hashtable; however, if the order of the properties was to remain fixed then an additional data structure would be required to list their order.
Upvotes: 0