Before you tag this as duplicate - I\'ve gone through these answers:
Sort JSON by array key value
Sort a JSON array object using Javascript by value
I created these functions to order a json so that it would also work if there was another json inside it.
function orderJson(json) {
let ordered = this.jsonToSortedArray(json);
let result = this.arrayToStringJson(ordered);
return JSON.parse(result);
}
function jsonToSortedArray(json) {
let ordered = [];
for (let i in json) {
let value;
if (json[i] instanceof Object) {
value = jsonToSortedArray(json[i]);
} else {
value = json[i];
}
ordered.push([i, value]);
}
return ordered.sort();
}
function arrayToStringJson(ordered) {
let result = '{'
for (let i = 0; i < ordered.length; i++) {
const key = '"' + ordered[i][0] + '"';
let value;
if (ordered[i][1] instanceof Array) {
value = ':' + this.arrayToStringJson(ordered[i][1]) + ',';
} else {
value = ':"' + ordered[i][1] + '",';
}
result += key + value;
}
result = result.substring(0, result.length - 1);
return result + '}';
}
If you want the json as a string do not use the function JSON.parse