Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

jquery - How to get the JSON with duplicate keys completely in javascript

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? Here is my js Code

$('document').ready(function(){
    var s = $.getJSON("new.json");
    console.log(s);
});

following is my new.json

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

But in console i am getting the json Object as follows

responseJSON: Object
s: "asd"

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"]}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...