PHP json_decode()在看似有效的JSON中返回NULL?

171

我有一个存储在纯文本文件中的JSON对象:

{
    "MySQL": {
        "Server": "(server)",
        "Username": "(user)",
        "Password": "(pwd)",
        "DatabaseName": "(dbname)"
    },
    "Ftp": {
        "Server": "(server)",
        "Username": "(user)",
        "Password": "(pwd)",
        "RootFolder": "(rf)"
    },
    "BasePath": "../../bin/",
    "NotesAppPath": "notas",
    "SearchAppPath": "buscar",
    "BaseUrl": "http:\/\/montemaiztusitio.com.ar",
    "InitialExtensions": [
        "nem.mysqlhandler",
        "nem.string",
        "nem.colour",
        "nem.filesystem",
        "nem.rss",
        "nem.date",
        "nem.template",
        "nem.media",
        "nem.measuring",
        "nem.weather",
        "nem.currency"
    ],
    "MediaPath": "media",
    "MediaGalleriesTable": "journal_media_galleries",
    "MediaTable": "journal_media",
    "Journal": {
        "AllowedAdFileFormats": [
            "flv:1",
            "jpg:2",
            "gif:3",
            "png:4",
            "swf:5"
        ],
        "AdColumnId": "3",
        "RSSLinkFormat": "%DOMAIN%\/notas\/%YEAR%-%MONTH%-%DAY%\/%TITLE%/",
        "FrontendLayout": "Flat",
        "AdPath": "ad",
        "SiteTitle": "Monte Maíz: Tu Sitio",
        "GlobalSiteDescription": "Periódico local de Monte Maíz.",
        "MoreInfoAt": "Más información aquí, en el Periódico local de Monte Maíz.",
        "TemplatePath": "templates",
        "WeatherSource": "accuweather:SAM|AR|AR005|MONTE MAIZ",
        "WeatherMeasureType": "1",
        "CurrencySource": "cotizacion-monedas:Dolar|Euro|Real",
        "TimesSingular": "vez",
        "TimesPlural": "veces"
    }
}
当我尝试使用 json_decode() 解码它时,返回了 NULL。为什么会这样呢?文件是可读的(我尝试使用 file_get_contents() 输出并且可以正常工作)。我已经在 http://jsonlint.com/ 进行了 JSON 验证,它是完全有效的。这里出了什么问题?

7
我正在使用 PHP 5.2.9,因此无法使用 json_last_error() - Joel A. Villarreal Bertoldi
1
还要注意的是,文件中间可能存在其他无效字符导致这种情况发生。我曾经遇到过json_decode()返回null的情况,因为字符串包含一个特殊的en-dash,可能是从MS Word复制粘贴而来,然后可能出现了误编码。为了识别潜在的问题字符,打开JSON文件(我用的是Notepad++),更改编码(不要进行转换),并另存为副本。然后比较两个文件的差异(我使用的是WinMerge)。 - LinusR
(Windows 记事本问题)请参考此链接,我也遇到了同样的问题,通过这个链接解决了:https://dev59.com/y2kv5IYBdhLWcg3w4kl2 - Felix Aballi
可能是重复的问题:json_decode 在调用 Web 服务后返回 NULL - user
对我来说,这并不是什么特别的事情,只是一个对象元素末尾多了一个逗号而已。重点是:任何使您的 JSON 不一致的因素都会引发错误。额外提示:不要相信 jsonviewer.stack.hu,使用类似 jsonlint 的工具。 - Aman Alam
@Cristik 问我在11年后编辑问题有点有趣,哈哈。无论如何,我会进行编辑以澄清。 - Joel A. Villarreal Bertoldi
29个回答

1
我建议创建一个 .json 文件(例如:config.json)。然后将您的 JSON 对象全部粘贴并进行格式化。这样,您就能够删除所有破坏您 JSON 对象的内容,并获得干净的复制粘贴 JSON 对象。

0
我通过打印JSON并检查页面源代码(CTRL/CMD + U)解决了这个问题。
print_r(file_get_contents($url));

原来有一个尾随的<pre>标签。

0
在应用 PHP 相关的解决方案之前,请验证您的 JSON 格式。也许这就是问题所在。尝试使用 在线 JSON 格式验证器

0
对于我的情况来说,是因为JSON字符串中有单引号。
JSON格式只接受双引号作为键和字符串值。
示例:
$jsonString = '{\'hello\': \'PHP\'}'; // valid value should be '{"hello": "PHP"}'
$json = json_decode($jsonString);
print $json; // null

我因为JavaScript语法而感到困惑。在JavaScript中,当然我们可以这样做:

let json = {
    hello: 'PHP' // no quote for key, single quote for string value
}

// OR:
json = {
    'hello': 'PHP' // single quote for key and value
}

但是当将这些对象转换为JSON字符串时:

JSON.stringify(json); // "{"hello":"PHP"}"

0

你应该确保以下几点:

1. 你的 JSON 字符串不含任何未知字符。

2. JSON 字符串可以在在线 JSON 查看器中查看(你可以在 Google 上搜索“JSON 在线查看器或解析器”),它应该没有任何错误。

3. 你的字符串不含 HTML 实体,它应该是纯文本/字符串。

关于第三点的解释:

$html_product_sizes_json=htmlentities($html);
    $ProductSizesArr = json_decode($html_product_sizes_json,true);

转换为(移除 htmlentities() 函数)

$html_product_sizes_json=$html;
    $ProductSizesArr = json_decode($html_product_sizes_json,true);

-2

我曾经遇到过完全相同的问题 但是这段代码解决了它

$zip = file_get_contents($file);
$zip = json_decode(stripslashes($zip), true);

-2

我有同样的问题,但是其中任何一个答案都没有帮助我。 我的JSON对象中的一个变量的值为安达曼和尼科巴。我移除了这个&,然后我的代码完美地工作了。


-2

对我来说,我必须关闭error_reporting才能使json_decode()正常工作。听起来很奇怪,但在我的情况下是真的。因为在我尝试解码的JSON字符串之间打印了一些通知。


-6
<?php 
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},

]',"}

]",$json);
$data = json_decode($json);

echo "<pre>";
print_r($data);
echo "</pre>";
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接