How to get the JSON with duplicate keys completely in javascript

前端 未结 5 1616
后悔当初
后悔当初 2020-11-30 13:07

I am trying to get JSON from the url, But in the response object duplicate keys are removed. Is there any way to fetch it completely without removing the duplicate keys? Her

5条回答
  •  天涯浪人
    2020-11-30 13:38

    If you can't change the server response, for simple JSON data you can request the json like text and parse it like a string:

    var check = new RegExp('["\']([^\'"]*)[\'"][^:]*:[^"\']*["\']([^\'"]*)[\'"]',"g");
        $.ajax({
            url : "text.json",
            dataType : "text",
            success : function(data){
                var newData = {};
                data.replace(check,function(a,b,c){
                    if(typeof newData[b] == "undefined"){
                        newData[b] = c;
                    }else if(typeof newData[b] == "object"){
                        newData[b].push(c);
                    }else{
                        var ca = newData[b];
                        newData[b] = [ca,c];                     
                    }
                    return a;
                });
                console.log(newData);
                console.log($.parseJSON(data));
            },
            error : function(e,a){
                console.log(e,a);
            }
        });
    

    in this code newData with your json is:

    {"s": ["wae","asd"]}
    

提交回复
热议问题