2

I have an js object like

{
  a: 1,
  b: 2,
  c: 3
}

I wanted to stringify the above object using JSON.stringify with the same order. That means, the stringify should return me the strings as below,

"{"a":"1", "b":"2", "c":"3"}"

But it is returning me like the below one if my js object has too many properties say more than 500,

"{"b":"2", "a":"1", "c":"3"}"

Is there any option to get my js object's json string as in sorted in asc.

Thaadikkaaran
  • 5,088
  • 7
  • 37
  • 59
  • 4
    The order of properties in an object is not specified, and shouldn't be important. – Barmar Feb 03 '14 at 07:02
  • I am getting the same order as you expected. Check http://jsbin.com/ApUWOzaM/1 – Dhanu Gurung Feb 03 '14 at 07:03
  • 2
    If order matters to you, figure out how to represent the data structure as an array. – Anthony Chu Feb 03 '14 at 07:04
  • You can order it when you output it. Take the keys with `Object.keys`, sort them, then loop and access the object's property. – elclanrs Feb 03 '14 at 07:07
  • You want to sort an object, you can check post: http://stackoverflow.com/questions/5467129/sort-javascript-object-by-key – vaibhav silar Feb 03 '14 at 07:09
  • the stringified result should be sorted by when the key was added, unless the key was a number - as it seems to put number-keys first. http://jsfiddle.net/Sammons/8cZwf/ – Catalyst Feb 03 '14 at 07:12
  • Actually i am getting the application label strings [500+] as an js object [properties are in alphabetic order] from API & trying to stringify it. But the string returned from the JSON.stringify is not in alphabetic order. If i want to order it then it may take an hour... – Thaadikkaaran Feb 03 '14 at 07:19
  • @Jagan: But the problem is that properties in a JavaScript object are *not* in alphabetic order, so you're using the wrong data structure. – Blender Feb 03 '14 at 08:24
  • @Blender But mine is in alphabetic order [sorted manually]. – Thaadikkaaran Feb 03 '14 at 08:30
  • Properties don't remember the order you put them in. – Barmar Feb 03 '14 at 10:16
  • @Barmar I just wanted to stringify the JS Object once it is ordered. I no more use it further. – Thaadikkaaran Feb 03 '14 at 11:28
  • You don't get it -- Javascript objects are not ordered in the first place. – Barmar Feb 03 '14 at 11:30
  • I dont want the JS object's properties to be sorted, But the JSON string of JS Object. I formed my JSON String using the Mehran Hatami 's approach. – Thaadikkaaran Feb 03 '14 at 11:35

2 Answers2

3

If the order is important for you, don't use JSON.stringify because the order is not safe using it, you can create your JSON stringify using javascript, to deal with string values we have 2 different ways, first to do it using regexp an replace invalid characters or using JSON.stringify for our values, for instance if we have a string like 'abc\d"efg', we can simply get the proper result JSON.stringify('abc\d"efg'), because the whole idea of this function is to stringify in a right order:

function sort_stringify(obj){
    var sortedKeys = Object.keys(obj).sort();
    var arr = [];
    for(var i=0;i<sortedKeys.length;i++){
        var key = sortedKeys[i];
        var value = obj[key];
        key = JSON.stringify(key);
        value = JSON.stringify(value);
        arr.push(key + ':' + value);
    }
    return "{" + arr.join(",\n\r") + "}";
}
var jsonString = sort_stringify(yourObj);

If we wanted to do this not using JSON.stringify to parse the keys and values, the solution would be like:

function sort_stringify(obj){
    var sortedKeys = Object.keys(obj).sort();
    var arr = [];
    for(var i=0;i<sortedKeys.length;i++){
        var key = sortedKeys[i];
        var value = obj[key];
        key = key.replace(/"/g, '\\"');
        if(typeof value != "object")
            value = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
        arr.push('"' + key + '":"' + value + '"');
    }
    return "{" + arr.join(",\n\r") + "}";
}
Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35
0

The JavaScript objects are unordered by definition (you may refer to ECMAScript Language Specification under section 8.6, click here for details ).

The language specification doesn't even guarantee that, if you iterate over the properties of an object twice in succession, they'll come out in the same order the second time.

If you still required sorting, convert the object into Array apply any sorting algorithm on it and then do JSON.stringify() on sorted array.

Lets have an example below as:

var data = {
    one: {
        rank: 5
    },
    two: {
        rank: 2
    },
    three: {
        rank: 8
    }
};

var arr = [];

Push into array and apply sort on it as :

var mappedHash = Object.keys( data ).sort(function( a, b ) {
    return data[ a ].rank - data[ b ].rank;
}).map(function( sortedKey ) {
    return data[ sortedKey ];
});

And then apply JSON.stringy :

var expectedJSON = JSON.stringify(mappedHash);

The output will be:

"[{"rank":2},{"rank":5},{"rank":8}]"
Mazzu
  • 2,799
  • 20
  • 30