How to change the order of the fields in JSON

May be you could change this using JSON.stringify()

do like

var json = {     "name": "David",     "age" : 78,     "NoOfVisits" : 4   };
console.log(json);
//outputs - Object {name: "David", age: 78, NoOfVisits: 4}
//change order to NoOfVisits,age,name

var k = JSON.parse(JSON.stringify( json, ["NoOfVisits","age","name"] , 4));
console.log(k);
//outputs - Object {NoOfVisits: 4, age: 78, name: "David"} 

put the key order you want in an array and supply to the function. then parse the result back to json. here is a sample fiddle.


Objects have no specific order.


Update:

ES3 Specs

An ECMAScript object is an unordered collection of properties

ES5 Specs

The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified.

Properties of the object being enumerated may be deleted during enumeration. If a property that has not yet been visited during enumeration is deleted, then it will not be visited. If new properties are added to the object being enumerated during enumeration, the newly added properties are not guaranteed to be visited in the active enumeration. A property name must not be visited more than once in any enumeration.


However. If you want to rely on the V8 implementations order.

Keep this in your mind.

When iterating over an Object, V8 iterates as followed

  1. Numeric properties in ascending order. (Though not guaranteed)
  2. Non-numeric properties in order of insertion.

Shown in following example

var a = {c:0,1:0,0:0};

a.b = 0;
a[3] = 0;
a[2] = 0;

for(var p in a) { console.log(p)};

gives the output

  1. 0
  2. 1
  3. 2
  4. 3
  5. b
  6. c

If you want guarantee order ...

you are forced to either use two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.

(MDN)