How to get JSON with duplicate keys completely in javascript

I'm trying to get JSON from url, but duplicate keys are being removed in the response object. Is there a way to get it completely without deleting the duplicate keys? Here is my js code

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

      

next my new.json

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

      

But in the console, I am getting json Object like this

responseJSON: Object
s: "asd"

      

Thank you in advance

+3


source to share


5 answers


The keys in the JSON object must be unique. Otherwise, the last key with a value is usually the one specified when requesting that key. Having keys in the same way also makes it difficult to distinguish between object attributes. The whole point of a key is to make it accessible and accessible.

To get around this, you can always:

  • Change the keys in your JSON
  • Change the JSON to contain an array

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

JavaScript Data Interchange Format (JSON)) (RFC7159) :

Names within an object MUST be unique.



In this context, it should be understood as specified in RFC 2119

SHOULD This word or the adjective "RECOMMENDED" means that there are valid reasons in specific circumstances to ignore but all consequences must be understood and carefully considered before choosing a different course.


RFC 7159 explains why unique keys are good:

An object whose names are unique is consistent in the sense that all software implementations receiving that object will agree on name mappings. When the names within an object are not unique, the behavior of the software that such an object receives is unpredictable. Many implementations only specify the surname / value pair
. Other implementations report an error or do not parse the object, and some implementations report all name / value pairs,
including duplicates.

It has been observed that JSON parsing libraries differ in whether or not they make the display order of object elements visible to software. Implementations whose behavior does not depend on a member ordering will be consistent in the sense that they will not be affected by these differences.

+3


source


You can try to use this structure to use the same key multiple times:

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

      



As suggested by Craicerjack, you can also use an array for multiple values ​​with a single key:

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

      

0


source


If you cannot change the server response, for simple JSON data, you can request json text and parse it as 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:

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

      

0


source


This is not possible with JSON.parse()

. I believe the more modern ES specification states that subsequent keys override previous ones.

However, the JSON spec doesn't prohibit JSON like this. And there are alternative parsers and serializers that can create and consume such JSON from JavaScript. For example, you can use a SAX clarinet style JSON parser :

const clarinet = require('clarinet');

const parser = clarinet.parser();
const result = [];
parser.onkey = parser.onopenobject = k => {
    result.push({key: k, value: null});
};
parser.onvalue = v => {
    result[result.length - 1].value = v;
};
parser.write('{"a": "1", "a": "2"}').close();

console.log(result);
// [ { key: 'a', value: '1' }, { key: 'a', value: '2' } ]

      

If you're wondering how to use require()

in a browser, check out how to use webpack .

0


source


Let's say you have data like this ...

country: {
    "name" : "America",
    "name" : "India",
    "name" : "Japan"
}

      

If you want to parse it, change the json to something like this ...

country: {
    "name1" : "America",
    "name2" : "India",
    "name3" : "Japan"
}

      

Then during parsing use ...

Object.keys(country).map(function(key) {
    if(key.match(/name/) == "name"){
        console.log(country[key],"is the value");
    }
});

      

Hope it helps.

-1


source







All Articles