首页 > 解决方案 > 检查未定义类型的 JSON 响应

问题描述

不久前我问了一个类似的问题,但意识到我离题了。我正在调用读取 JSON 文件并返回响应的后端

public function getData()
{
    return json_decode(file_get_contents($file_path, true));
}

从后端返回的文件采用以下形式

[
  [
    //Some data
  ],
  [
    //Some data
  ],
  [
    {
      "Category": "basketball",
      "Count": 12
    },
    {
      "Category": "football",
      "Count": 34
    },
    {
      "Category": "baseball",
      "Count": 244
    },
    {
      "Category": "softball",
      "Count": 11
    }
  ]
]

所以它是数组和对象数组的混合体。上面的对象数组是我感兴趣的。在前端,我正在尝试处理这些数据。目前我做类似的事情

const catOne = response.data[2][0]['Count'];
const catTwo = response.data[2][1]['Count'];
const catThree = response.data[2][2]['Count'];
const catFour = response.data[2][3]['Count'];

然而,我注意到的是,有时传回的文件没有 4 个类别。因此,我收到了错误

TypeError: Cannot read property 'Count' of undefined

我想知道处理这个问题的最佳方法是什么?我真的不想要大量的 if/else 语句,因为这看起来很乱。我可以进行某种类型的三元检查以查看该值是否未定义吗?

谢谢

标签: javascriptjson

解决方案


我将采用以下路径:创建一个类别数组,然后对其进行迭代以进行计数,因为您没有指定您的用例我不确定这是否适用于您。

但是你要做的事情是这样的:

const categories = [];
for ( let i = 0; i < response.data[2].length; i++) {
    let response_data = response.data[2][i];
    if (response_data !== undefined) {
         categories.push(response_data); // You could also be pushing the count in here
    }
}

推荐阅读