Sort JSON array after $.getJSON excecuted

前端 未结 2 1591
旧巷少年郎
旧巷少年郎 2021-01-26 18:37

I have a working connection between my json object and getJSON(). I can also sort the data i get once with this code, I sorted it on the \'name\' field of the array and it works

2条回答
  •  深忆病人
    2021-01-26 19:01

    Do this:

    var json = { users: [] };
    var url="http://localhost/api/users.php";
    $.getJSON(url,function(response){
        json = response;
    });
    
    function sortJsonField(field){
    
        function sortJson(a,b){
            if(field == "id"){ return a.id > b.id? 1 : -1; }else
            if(field == "job"){ return a.job > b.job? 1 : -1; }else
            return a.name > b.name? 1 : -1;
        }
    
        // No need to assign this to a new array.
        json.users.sort(sortJson);
    
        showJSON();
    };
    
    function showJSON(){
    
        // May empty the ul/ol before doing this? up to you..
        $.each(json.users,function(i,row){ 
            $("#output").append(
                '
  • ' + row.id + row.name + row.job + '
  • ' ); }); };

    EDIT: Also, the JSON structure is slightly incorrect...

    Change this:

    {"users":[
    {"id":"1","name":"John","job":"worker"}
    {"id":"2","name":"Mike","job":"innovator"}
    {"id":"3","name":"Anna","job":"reader"}
    ]}
    

    ....to this:

    {"users":[
    {"id":"1","name":"John","job":"worker"},     // <--- Do you see the commas here?
    {"id":"2","name":"Mike","job":"innovator"},    // <--- and here?
    {"id":"3","name":"Anna","job":"reader"}
    ]}
    

    The objects are well-formed, but that is not a valid array, so javascript breaks. Modify it and it should all work.

    P.S This is the url of the website I used to check your JSON structure: http://www.freeformatter.com/json-validator.html

提交回复
热议问题