Sort JSON response by key value

后端 未结 3 2096
半阙折子戏
半阙折子戏 2021-01-20 16:57

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

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-20 17:47

    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

提交回复
热议问题