Mohit Verma
Mohit Verma

Reputation: 1660

Duplicate keys in JSON

How can i parse and show error if given JSON contains duplicate keys. JSON.parse just ignores it & pick last key value.Also let me know if any sort of npm lib available for the same.

{
  "name":"mohit",
  "name":"verma"
}

Upvotes: 1

Views: 2766

Answers (1)

code_monk
code_monk

Reputation: 10128

If you can predict how the JSON will be formatted*, you can compare to the text to the result of parsing and re-stringifying the object:

  • See comments below for a description of cases where this would fail

const hasDuplicateKey = (j) => {
    let k = JSON.stringify(JSON.parse(j));
    let h = JSON.stringify(JSON.parse(j),null,"  ");
    return !(j === h || j === k);
};

let json1 = `{"name":"bob","name":"alice","age":7}`;
let json2 = `{"name":"bob","age":7}`;

let json3 = `{
  "name": "mohit",
  "name": "verma"
}`;

let json4 = `{
  "name": "mohit",
  "age": 107
}`;

console.log( hasDuplicateKey(json1) );
console.log( hasDuplicateKey(json2) );
console.log( hasDuplicateKey(json3) );
console.log( hasDuplicateKey(json4) );

Upvotes: 5

Related Questions