Here is my nested JSON object
var dataSource = ({
"Items": ({
"Deserts": ({}),
"Veg": ({
"VegPulao": "Veg Pulao",
"PalakPaneer": "Palak Paneer",
"PaneerButterMasala": "Paneer Butter Masala"
}),
"Chicken": ({
"Tandoori": "Tandoori special"
}),
"Hot drinks": ({
"Coffe": ({ "Hot": "Hot Coffe", "Medium": "Medium", "Others": ({ "Iris": "Iris Coffe", "Capuccino": "Capuccino" }) }),
"Tea": ({ "Red": "Red Tea", "Black": "Black Tea" }),
"Hot BadamMilk": "Hot Badam Milk",
"Hot Bornvita": "Hot Bornvita",
"Hot Milk": "Hot Milk"
}),
"Juice": ({
"Mango": "Mango",
"Berry": "Berry",
"Grapes": "Grapes",
"Wine": ({
"Rose": "Rose",
"Red wine": "Red",
"Apple": "Apple",
"Hard drinks": ({
"Royal challenge": "Royal challenge",
"Blender's Pride": "Blender's Pride"
})
})
})
})
});
I want this JSON object to be sorted
var dataSource = ({
"Items": ({
"Deserts": ({}),
"Veg": ({
"VegPulao": "Veg Pulao",
"PalakPaneer": "Palak Paneer",
"PaneerButterMasala": "Paneer Butter Masala"
}),
"Chicken": ({
"Tandoori": "Tandoori special"
}),
"Hot drinks": ({
"Coffe": ({ "Hot": "Hot Coffe", "Medium": "Medium", "Others": ({ "Iris": "Iris Coffe", "Capuccino": "Capuccino" }) }),
"Tea": ({ "Red": "Red Tea", "Black": "Black Tea" }),
"Hot BadamMilk": "Hot Badam Milk",
"Hot Bornvita": "Hot Bornvita",
"Hot Milk": "Hot Milk"
}),
"Juice": ({
"Mango": "Mango",
"Berry": "Berry",
"Grapes": "Grapes",
"Wine": ({
"Rose": "Rose",
"Red wine": "Red",
"Apple": "Apple",
"Hard drinks": ({
"Royal challenge": "Royal challenge",
"Blender's Pride": "Blender's Pride"
})
})
})
})
});
I want this JSON object to be sorted
I m having 2 solutions to solve this problem.
ReplyDeleteFirst will return a sorted JSON object and
Second will return a sorted JSON as string.
Here s the first solution of returning as a sorted json object
ReplyDelete//Function to sort
function returnSortedJsonObject(obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}
keys.sort();
var tempObj = new Object();
for (var i = 0; i < keys.length; i++) {
for (var key in obj) {
if (keys[i] == key) {
if (typeof obj[key] == 'object')
obj[key] = returnSortedJsonObject(obj[key]);
tempObj[key] = obj[key];
}
}
}
return tempObj;
}
//Calling the method
var SortedJSON=returnSortedJsonObject(dataSource);
Here s the second solution to return the sorted json object as a string...
ReplyDelete//Function to sort
function returnSortedJsonString(obj) {
var retValue = ""
var keys = [];
for (var key in obj) {
keys.push(key);
}
keys.sort();
var i = 0;
for (var key in obj) {
key = keys[i++];
if (typeof obj[key] == 'object') {
retValue += '"' + key + '" : ({ ';
retValue += returnSortedJsonString(obj[key])
retValue += ' }), '
}
else {
retValue += '"' + key + '" : "' + obj[key] + '", ';
}
}
retValue = retValue.substring(0, (retValue.length - 1));
return retValue;
}
//Calling the method
var jsonString = "({ " + returnSortedJsonString(dataSource) + " });";
var SortedJSON=eval(jsonString);