Values get rearranged by JSONObject constructor

I have this:

String foo = 

    "options": {
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
    }

But the JSONObject constructor rearranges the keys:

new JSONObject(foo).toString() = 

    "options": {
      "6",
      "3",
      "7",
      "2",
      "5",
      "1",
      "4",
      "8",
      "9",
    }

The new order is reproducible, meaning each execution results in the same (seemingly random) rearrangement.

Answers


That does not look like valid JSON to me. First, there is not {} or [] surrounding the entire string. Second, it looks like the data associated with options should be inside and array ([]) not be an object({}). If it was an array, the order would be preserved, whereas with the values just being declared as properties, there is no guarantee on their order.


In json sequence of the fields is not important, only their nesting.


Your example Strings are invalid JSON. You have a bare top-level field options, and no values for it's fields.

A javascript object, it's JSON representation, and in particular a JSONObject, do not guarantee an ordering of the fields.

From the JSONObject javadoc:

A JSONObject is an unordered collection of name/value pairs.

You can maintain an ordering by using an array. So if your data is or can be represented as an array - from your example it looks like an array - then the order of the elements will be maintained.


Need Your Help

ajax.js importing issue

javascript jquery ajax

In index.html i imported ajax.js with the code :

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.