简体   繁体   中英

How do I order items returned in JSON format?

I want to sort the following information by the string value (not the key number). I am able to convert it to a dictionary and order by value ("AAA" and "CCC") in the code below... now the only question is, how do I convert the dictionary to the same format below in the parseJSON function? I cannot change the format of the JSON so that's out of the question. Any other ways are appreciated. I cannot move it to an array or anything. As stated in my question, the JSON format exists as is and I cannot change it.

   var studentCollection.Groups = $.parseJSON("{\"1000\":\"CCC\", \"1001\":\"AAA\"}");

    //Sorting the studentCollection.Groups dictionary. 
    //Even though the groups come back as valid/sorted JSON
    //upon parsing the JSON, the groups sorting gets lost
    var items = Object.keys(studentCollection.Groups).map(function (key) {
        return [key, studentCollection.Groups[key]];
    });

    items.sort(function (first, second) {

        if (first[1] < second[1])
            return -1;
        if (first[1] > second[1])
            return 1;
        return 0;

    });

you can just convert your object values to array which you will sort and then again assign step-by-step to an object:

    var j = "{\"1000\":\"AAA\", \"1001\":\"ZZZ\"}";
    var o = JSON.parse(j);

    var keys = Object.keys(o);
    var values = [];

    for(var i = 0; i < keys.length; i++) values.push(o[keys[i]]);

    values.sort();

    for(var i = 0; i < values.length; i++) o[keys[i]] = values[i];

    alert( JSON.stringify(o) );

UPDATE

since example above has not keep the keys base order this one should:

    var j = "{\"1000\":\"AAA\", \"1002\":\"ZZZ\", \"1004\":\"DDD\", \"1003\":\"BBB\", \"1001\":\"YYY\"}";

    j = j.replace(/\"\d+\"\:/g, function myFunction(x){ return x.substring(0,1) + "_" + x.substring(1) })

    var o = JSON.parse(j);

    var keys = Object.keys(o);
    var values = [];

    for(var i = 0; i < keys.length; i++) values.push(o[keys[i]]);

    values.sort();

    for(var i = 0; i < values.length; i++) o[keys[i]] = values[i];

    var j = JSON.stringify(o)

    j = j.replace(/\"\_\d+\"\:/g, function myFunction(x){ return x.substring(0,1) + x.substring(2) })

    alert( j );

try it here: https://jsfiddle.net/pyqw8hvt/1/

the idea is to add _ before every integer key to make it non-integer and in this way avoid automatic sorting inside parsed object, and then after stringifying the object erase the added _ inside keys

I don't know if this is the best way to do it, you'd have to call JSON.stringify twice, but it gives the output you're looking for:

var studentCollection = {};
studentCollection.Groups = $.parseJSON("{\"1000\":\"CCC\", \"1001\":\"AAA\"}");

var items = Object.keys(studentCollection.Groups).map(function (key) {
    return [key, studentCollection.Groups[key]];
});

items.sort(function (first, second) {
    if (first[1] < second[1])
        return -1;
    if (first[1] > second[1])
        return 1;
    return 0;
});

result = JSON.stringify(JSON.stringify(toObject(items)))
console.log(result);
// outputs: "{\"1001\":\"AAA\",\"1000\":\"CCC\"}"

// checking if ordering remains
console.log($.parseJSON(result));
// outputs: {"1001":"AAA","1000":"CCC"}

function toObject(arr) {
    return arr.reduce(function(o, v, i) {
        o[v[0]] = v[1];
        return o;
    }, {});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM