Skip to content Skip to sidebar Skip to footer

Stringify An Js Object In Asc Order

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

Solution 1:

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:

functionsort_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:

functionsort_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") + "}";
}

Solution 2:

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:

vardata= {
    one: {
        rank:5
    },
    two: {
        rank:2
    },
    three: {
        rank:8
    }
};vararr= [];

Push into array and apply sort on it as :

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

And then apply JSON.stringy :

var expectedJSON = JSON.stringify(mappedHash);

The output will be:

"[{"rank":2},{"rank":5},{"rank":8}]"

Post a Comment for "Stringify An Js Object In Asc Order"