【发布时间】:2020-02-10 14:05:34
【问题描述】:
我正在解析 JSON 并尝试访问其中一个字段,即一个数组。
const myObj: MyObj = JSON.parse(myJson);
console.log(myObj.myArray); //SyntaxError: Unexpected end of JSON input
console.log(myObj.myArray == 'undefined'); //SyntaxError: Unexpected end of JSON input
console.log(myObj.myArray.length); //TypeError: Cannot read property 'length' of undefined
console.log(myObj.myArray !== null); //true
我没有问题遍历我的数组并使用数据做我需要的事情。但我需要检查以确保 myArray 字段在遍历它时是有效的。当我尝试执行此操作时,我收到如上所示的错误。
我很困惑。谁能向我解释发生了什么以及如何解决它?
【问题讨论】:
-
你能做一个运行的例子吗?包括(部分)json
-
看起来你的 json 无效,使得任何后续操作都毫无意义。
-
console.log(typeof myObj)返回什么?
标签: javascript arrays node.js json typescript