Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the order of the fields in JSON

Tags:

json

node.js

Scenario: Consider I have a JSON documents as follows:

   {
     "name": "David",
     "age" : 78,
     "NoOfVisits" : 4
   }

Issues: I wanted to change the sequence/order of the fields in the document, say I want age, NoOfVisits & then lastly name.

As of now I am storing the value in temporary variable, deleting the field & recreating the same field. Since the reassignment did not work :(

I did it in following way:

    temp = doc["age"];
    delete doc['age'];
    doc["age"] = temp;

    temp = doc["NoOfVisits "];
    delete doc['NoOfVisits '];
    doc["NoOfVisits"] = temp;

    temp = doc["name"];
    delete doc['name'];
    doc["name"] = temp;

So that I will get the desired ordered JSON document. This requirement is peculiar kind but still I want some efficient solution

Question: Can someone help out with efficient way to achieve the same?

like image 261
Amol M Kulkarni Avatar asked May 14 '13 11:05

Amol M Kulkarni


People also ask

Does order of fields matter in JSON?

what is the use for order the fields? From json.org "An object is an unordered set of name/value pairs." You should write your JSON processor so that order doesn't matter.

Does JSON maintain order?

Yes, the order of elements in JSON arrays is preserved.

How do I sort items in JSON?

Example-1: Sort JSON object using json. dumps() The value of the sort_keys argument of the dumps() function will require to set True to generate the sorted JSON objects from the array of JSON objects. Create a python file with the following script sort the JSON objects using json. dumps() function.

What is the syntax to order the key in JSON file?

In the JSON data format, the keys must be enclosed in double quotes. The key and value must be separated by a colon (:) symbol. There can be multiple key-value pairs. Two key-value pairs must be separated by a comma (,) symbol.


2 Answers

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.

like image 175
Mithun Satheesh Avatar answered Oct 11 '22 10:10

Mithun Satheesh


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)

like image 24
Moritz Roessler Avatar answered Oct 11 '22 10:10

Moritz Roessler