如果给定的JSON包含重复键,我如何解析并显示错误。 JSON.parse只是忽略它&选择最后一个键值。如果有任何类型的npm lib可用,请告诉我。
{
"name":"mohit",
"name":"verma"
}
答案 0 :(得分:3)
如果您可以预测JSON的格式化方式*,则可以将文本与解析和重新字符串化对象的结果进行比较:
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) );