解析返回的 JSON 数据时出错

问题描述 投票:0回答:1

这是一个精简的片段,在旧网站上运行良好。 但是我现在得到以下内容

"Warning: Trying to access array offset on value of type null"
"Fatal error: Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, null given"

这是 JSON 数据的片段:

$file = '
{
"total_entries" : 912,
  "jobs": [
    {
      "title": "Business Intelligence VBA Developer",
      "logo": "https://myurl/logo/big/b7499f6a58974564859a309442fc4b52",
      "type": [
        "Permanent"
      ],
      "salary": "£49500 - £66000/annum",
      "expiry_date": "2024-11-21T01:08:04Z",
      "applications": "10+",
      "posted": "2024-10-24T01:08:04Z",
      "id": 222536673,
      "hl_title": "Business Intelligence VBA \u003Cem\u003EDeveloper\u003C/em\u003E",
      "url": "/job/222536673/Business-Intelligence-VBA-Developer?hlkw=Developer&s=101899",
      "location": "KT5 9NU",
      "description": "Business Intelligence VBA \u003Cem\u003EDeveloper\u003C/em\u003E. Summary. £49,500* up to £66,000 per annum* | 35 days holiday (pro rata) | 10% in-store discount | Pension scheme. Everyone who works at Lidl brings something unique to the table - but we also have a whole lot in common. Were proactive, reliable and  …",
      "agency": {
        "url": "https://myurl/list-jobs/226772/Lidl",
        "title": "Lidl",
        "type": "Corporate"
        }
    }
    ]
}';
$data = json_decode($file, true);
$specified = $data['total_entries'];
$total_entries = count($data['jobs']);
echo $specified.'<br>';
echo "Total Entries: " . $total_entries;

它在我活跃的其他网站上运行得很好,所以我不确定为什么我现在收到错误。

任何想法将不胜感激

php json
1个回答
0
投票

该问题可能与您的 PHP 版本有关,因此它可以在旧网站上运行,而不是在新网站上运行。在较新的 PHP 版本中,

null
键的处理方式有所不同,并且在以前不会的情况下会触发警告。

为了解决这个问题,我将进行一项检查,以确保 JSON 被正确解码,并且在调用

jobs
之前,
count()
存在并且是一个数组。

下面的代码将检查

$data
是否为 null,表示 JSON 解码失败,并在调用
$data['jobs']
之前检查
count()
是否存在并且是一个数组。

$data = json_decode($file, true);

if ($data === null) {
    echo "Error decoding JSON data.";
} else {
    $specified = isset($data['total_entries']) ? $data['total_entries'] : 0;
    $total_entries = isset($data['jobs']) && is_array($data['jobs']) ? count($data['jobs']) : 0;

    echo $specified . '<br>';
    echo "Total Entries: " . $total_entries;
}
© www.soinside.com 2019 - 2024. All rights reserved.