【问题标题】:json_decode returning NULL with valid JSON datajson_decode 返回 NULL 和有效的 JSON 数据
【发布时间】:2015-09-01 14:56:26
【问题描述】:

这是我的 JSON 解析器函数中的一个 sn-p 代码,它可以很好地处理大约十几个不同的 JSON 文件:

打印件用于当前的调试目的

    $this->response = stripslashes($this->response);
    print_r($this->response);
    $this->response = json_decode($this->response);
    print_r($this->response);

第一次打印给我 JSON 字符串,第二次打印给我 null。使用 json_last_error 我设法发现 PHP 拒绝解析 JSON,因为它的语法无效。

这是我正在解析的 JSON (full thing here) 的片段,它使用我可以在 Google 上找到的每个验证器进行验证:

{
"success": 1,
"stores": [
    {
        "name": "Winton",
        "address": "370-374 , Wimborne Road, Bournemouth, Dorset BH92HE",
        "telephone": "",
        "email": "info@99pstoresltd.com",
        "website": "",
        "description": "Mon  - 09.00-18.00  Tue - 09.00-18.00  Wed - 09.00-18.00  Thu - 09.00-18.00  Fri - 09.00-18.00  Sat - 09.00-18.00  Sun - 10.00-16.00",
        "lat": "50.7413",
        "lng": "-1.87926",
        "titlewebsite": "Website",
        "titleemail": "Email",
        "titletel": "Telephone",
        "titlecontactstore": "Contact this store",
        "titlekm": "km",
        "titlemiles": "miles",
        "cat_name": "",
        "cat_img": "",
        "img": ""
    },
    {
        "name": "Boscombe",
        "address": "The Sovereign Centre, Boscombe, Bournemouth, Dorset BH14SX",
        "telephone": "",
        "email": "info@99pstoresltd.com",
        "website": "",
        "description": "Mon  - 08.00-18.00  Tue - 08.00-18.00  Wed - 08.00-18.00  Thu - 08.00-18.00  Fri - 08.00-18.00  Sat - 08.00-18.00  Sun - 10.00-16.00",
        "lat": "50.7272",
        "lng": "-1.83952",
        "titlewebsite": "Website",
        "titleemail": "Email",
        "titletel": "Telephone",
        "titlecontactstore": "Contact this store",
        "titlekm": "km",
        "titlemiles": "miles",
        "cat_name": "",
        "cat_img": "",
        "img": ""
    }]
}

我不知道为什么这不是解析,因为 JSON 对我来说看起来不错!已经盯着这个看了很长一段时间了,所以很高兴在这里对此有一些想法。

编辑: 从第一个 print_r 复制并粘贴数据并将其推送到 json_decode 工作正常。我假设这意味着 JSON 的来源存在问题,可能会弄乱编码或其他什么?

【问题讨论】:

  • 不知道为什么我以前没有尝试过,但如果我使用 pastebin 中的数据,它也能很好地解析我。但是,这与第一个 print_r 给我的数据完全相同(我从那个 print_r 复制并粘贴了那个 pastebin)。这是否意味着这是某种编码问题?
  • 解析对我来说也很好,你检查过可能的编码问题吗?你为什么要运行stripslashes?
  • 我尝试使用iconv() 来确保字符串为 UTF-8 格式,但我不确定如何实际检查编码是否正确(我的客户端没有访问权限给我这个json响应的服务器代码)。 stripslashes 被放在那里以容纳一些通过函数的其他 JSON 字符串,我已经删除了 stripslashes 但仍然遇到同样的问题。
  • @jackmullen 如果为您提供了有效的 JSON 格式数据,则根据定义,它是 UTF-8,并且任何转义序列都已应用于 JSON。你只需要json_decode()它。
  • @MikeBrant 为我服务 JSON 的服务器代码正在使用 json_encode() (这就是我真正知道的关于如何/发送给我的内容),所以在这种情况下 JSON 应该是格式和编码是否正确?但是,json_decode() 仍然给我一个空值。

标签: php json validation


【解决方案1】:

试试这个:

json_decode($this->response, true);

来自关于第二个参数的文档

当 TRUE 时,返回的对象将被转换为关联数组。

来源:http://php.net/manual/en/function.json-decode.php

【讨论】:

    猜你喜欢
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    相关资源
    最近更新 更多