我刚刚发现 JSON 可以将数字和字符串作为原始数据处理。我非常想知道为什么,因为我从未见过基元与 JSON 一起使用。
但是,对我来说,使用 JSON 解析基元更有可能是一个编程错误(不会被注意到),我想避免它。
例如,我可以强制抛出以下内容吗?
JSON.parse(123);
最佳答案
您可以包装 parse
函数并在反序列化之前检查 number
参数。
(() => {
const parse = JSON.parse;
JSON.parse = function (text,reviver) {
if (typeof text === "number") throw "JSON.parse: Invalid argument type (number)";
return parse(text,reviver);
}
})();
console.log( JSON.parse(`{"prop":"Hello world!"}`) ); //OK
console.log( JSON.parse(123) ); //NOT OK
关于javascript - 如何强制 JSON.parse 抛出数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59975658/