You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP:直接声明的JSON可解析,TXT读取后json_decode返回NULL的问题

问题描述

当执行以下代码时:

$res1 = '{"n":2,"stuff":[{"key1":"value1","key2":"value2"}]}';
$res1 = json_decode($res);
var_dump($res1);

输出结果为:

object(stdClass)#289 (2) { ["n"]=> int(2) ["stuff"]=> array(1) { [0]=> object(stdClass)#288 (2) { ["key1"]=> string(6) "value1" ["key2"]=> string(6) "value2" } } }

但将$res1的内容保存到名为string.txt的文本文件中,文件内容为:

'{"n":2,"stuff":[{"key1":"value1","key2":"value2"}]}'

执行以下代码:

$filename = "path/string.txt";
$res2 = file_get_contents($filename);
$res2 = json_decode($res2);

输出结果为NULL。

请问如何让从TXT文件读取的JSON字符串能像直接声明的$res1一样被json_decode正常解析?

补充说明:未提及的失败原因是,代码编辑器不允许在声明$res1时使用撇号(如Name's),因此将撇号转义为\',而转义后的字符出现在了用于$res2的string.txt文件中。


解决方案

核心问题

从文件读取的字符串包含多余的外层单引号,且存在不符合JSON规范的转义字符(\'),这两个问题直接导致json_decode解析失败。

具体修复方法

  1. 修正文本文件内容(推荐)
    直接保存纯JSON格式内容到string.txt,不要加外层单引号:

    {"n":2,"stuff":[{"key1":"value1","key2":"value2"}]}
    

    若字符串需要包含撇号(如Name's),JSON规范允许直接写入,无需转义:

    {"name":"Name's Test"}
    
  2. 读取后预处理(无法修改文件时)
    如果不能直接修改文件,可在读取后清理无效字符:

    $filename = "path/string.txt";
    $res2 = file_get_contents($filename);
    // 移除首尾的单引号
    $res2 = trim($res2, "'");
    // 把错误的转义撇号还原为正常撇号
    $res2 = str_replace("\\'", "'", $res2);
    $res2 = json_decode($res2);
    var_dump($res2);
    
  3. 调试解析错误
    若仍失败,可通过以下代码查看具体错误原因:

    $res2 = json_decode($res2);
    if ($res2 === null) {
        echo json_last_error_msg();
    }
    

内容的提问来源于stack exchange,提问作者randomvalue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 01:15:33