前端开发问题:SyntaxError: “undefined“ is not valid JSON
- 在 JavaScript 开发,遇到如下问题
SyntaxError: "undefined" is not valid JSON
# 翻译SyntaxError:"undefined" 不是有效的 JSON
问题原因
- 当使用
JSON.parse()
时,传入了一个undefined
或字符串"undefined"
,而它不是有效的 JSON 字符串
问题复现
- 传入一个
undefined
const jsonStr = undefined;const jsonObj = JSON.parse(jsonStr);console.log(jsonObj);
# 输出结果Uncaught SyntaxError: "undefined" is not valid JSON
- 传入一个字符串
"undefined"
const jsonStr = "undefined";const jsonObj = JSON.parse(jsonStr);console.log(jsonObj);
# 输出结果Uncaught SyntaxError: "undefined" is not valid JSON