1

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"
}
Mohit Verma
  • 1,620
  • 2
  • 20
  • 30

1 Answers1

5

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) );
code_monk
  • 9,451
  • 2
  • 42
  • 41
  • 1
    That doesn't work. Passing JSON through parse and then stringify will normalise things like white space. You've got `k` and `h` to handle two different sets of normalisation, but that only works if the initial data meets those normalisation patterns. Change one bit of it to `let json2 = `{"name": "bob","age":7}`;` (with extra spaces) and you get false positives. – Quentin Dec 04 '16 at 07:50
  • that is why i qualified with "if you can predict how the JSON will be formatted" – code_monk Dec 04 '16 at 07:59
  • @code_monk: If if one can "predict" how the JSON is formatted, it still would have to follow the same formatting rules as `JSON.stringify`. So why not just say that? *"If the JSON is formatted the same way as the output produced by `JSON.stringify`, ...."*. – Felix Kling Dec 04 '16 at 08:02
  • i added said clarification – code_monk Dec 04 '16 at 08:24
  • 1
    This will fail on an input of `'{"a":1,"1":22}'` (in at least some native `JSON.parse/JSON.stringify` implementations, due to special rules for ordering numeric keys). Your condition of "works with" is too weak--it needs to say "if it is **guaranteed** that `JSON.stringify` on the result of `JSON.parse` is byte-for-byte **identical** with the original input to `JSON.parse`". However, this condition never holds for any known JSON libraries. Hence, this solution at best works only in limited situations. –  Dec 04 '16 at 09:17
  • i added said clarification – code_monk Dec 04 '16 at 23:46
  • 1
    can we remove whitespace from json string, then parse and stringify it & match with string ( in which white space was removed ) – Mohit Verma Dec 10 '16 at 20:57