【问题标题】:How can I check if my JSON field is defined?如何检查我的 JSON 字段是否已定义?
【发布时间】: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


【解决方案1】:

使用in 时要小心,因为它会搜索整个原型链。

const myJson = '{"a": 2}';
const myObj = JSON.parse(myJson);

console.log('constructor' in myObj); // true (BAD)

请尝试使用.hasOwnProperty(),如下所示:

const myJson = '{"a": 2}';
const myObj = JSON.parse(myJson);

console.log(myObj.hasOwnProperty("a")); // true
console.log(myObj.hasOwnProperty("constructor")); // false

【讨论】:

    【解决方案2】:

    如果你担心存在,你可以简单地检查一下

    if (myObj.myArray) {

    如果你想确认存在并确认它是一个数组

    if (myObj.myArray && Array.isArray(myObj.myArray) {

    【讨论】:

      【解决方案3】:

      您可以使用in 运算符来检查是否在对象原型链中指定了属性:

      const myJson = '{"a": 2}';
      const myObj = JSON.parse(myJson);
      
      console.log('myArray' in myObj); // false
      console.log('a' in myObj); // true

      或者,您可以检查该字段是否不是undefined(如果是,则在JSON.parse返回的对象中不存在),最安全的方法是使用typeof运算符:

      const myJson = '{"a": 2}';
      const myObj = JSON.parse(myJson);
      
      console.log(typeof myObj.myArray !== 'undefined'); // false
      console.log(typeof myObj.a !== 'undefined'); // true

      应避免与undefined(例如myObj.myArray !== undefined)直接比较,因为undefined 可以是overridden or shadowed。

      编辑:正如@OliveNi 指出的那样,in 运算符的使用是危险的,因为它贯穿整个原型链。为了更安全的检查(作为undefined 检查的替代方法),您可以使用hasOwnProperty,如his answer 中所示。

      【讨论】:

      • 小心in。看我的回答
      【解决方案4】:

      您可以检查几件事来验证传递的输入是否有效。

      • 检查数据类型:如果类型已经是对象,则无需再次解析。
      • 检查真实情况,即if(myObj.myArray) { }
      • 看起来 myJSON 正在返回一个空数组。即[]

      因此,当尝试解析 [] 时,它会返回 "" 并给出以下错误。

      SyntaxError: JSON 输入意外结束

      var myObj = JSON.parse([]);
      
      console.log(myObj.myArray);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-19
        • 2022-09-30
        相关资源
        最近更新 更多