PHP脚本使用json_decode无法正常解码JSON文件的问题排查
PHP迁移Java程序时JSON解码失败问题梳理
- 基本背景:正在将已有的Java程序重写为PHP版本,由于缺乏PHP开发经验,采用边拼凑代码边查阅资料的方式开发,当前卡在文件解码环节——原有Java版本借助GSON库可正常解码目标文件,PHP端始终解码失败,暂未明确排查方向
最初编写的基础代码
public $lieder; public function convertJSONtoARRAY($newJSONFile) { $stringJsonFileContents = file_get_contents("$newJSONFile"); $lieder = json_decode($stringJsonFileContents); }
配套的初版调用代码:
<?php include ('LiederEditor.php'); include ('Index.json'); $editor = new LiederEditor(); $editor -> convertJSONtoARRAY("Index.json"); echo var_dump("$editor->lieder"); ?>
优化调整后的代码版本
public $lieder; public function convertJSONtoARRAY($newJSONFile) { $stringJsonFileContents = file_get_contents("$newJSONFile"); $this ->lieder = json_decode($stringJsonFileContents,true); }
配套调整后的调用代码:
<?php include ('LiederEditor.php'); $editor = new LiederEditor(); $editor -> convertJSONtoARRAY("Index.json"); var_dump($editor->lieder); ?>
当前待解码的JSON文件内容片段
{ "id": 1, "number": "A01", "name": "Gaudeamus Igitur, Kindleben", "slug": "gaudeamus-igitur", "language": "lat", "category": "Traditionell", "year": 1781, "position": 10010, "url": "https://beta.acel.lu/group/songbook/gaudeamus-igitur", "update_time": 1504601629, "paragraphs": [ { "id": 1660, "type": "normal", "content": "|: Gaudeamus igitur\niuvenes dum sumus :|\npost iucundam iuventutem,\npost molestam senectutem,\n|: nos habebit humus! :|" }, { "id": 1661, "type": "normal", "content": "|: Ubi sunt qui ante nos\nin mundo fuere? :|\nvadite ad superos\ntransite ad inferos\n|: ubi iam fuere. :|" }, { "id": 1662, "type": "normal", "content": "|: Vita nostra brevis est,\nbrevi finietur, :|\nvenit mors velociter,\nrapit nos atrociter\n|: nemini parcetur! :|" }, { "id": 1663, "type": "normal", "content": "|: Vivat academia,\nvivant professores! :|\nvivat membrum quodlibet,\nvivant membra quaelibet,\n|: semper sint in flore! :|" }, { "id": 1664, "type": "normal", "content": "|: Vivant omnes virgines\nfaciles, formosae, :|\nvivant et mulieres,\ntenerae, amabiles,\n|: bonae, laboriosae :|" }, { "id": 1665, "type": "normal", "content": "|: Vivat et res publica,\net qui illam regit! :|\nvivat nostra civitas,\nmaecenatum caritas,\n|: quae nos hic protegit! :|" }
可直接定位的问题点
- 目标JSON文件结构不完整:当前提供的JSON内容缺少paragraphs数组的闭合标记
],以及整个根对象的闭合标记},属于截断的无效JSON结构。PHP的json_decode对JSON格式的严格度高于GSON库,这类结构不完整的内容会直接返回null导致解码失败 - 初版代码存在逻辑缺陷:初版方法内将解码结果赋值给局部变量
$lieder,没有绑定到类的$this->lieder属性,外部实例无法读取到对应值;同时初版调用代码错误使用include 'Index.json'引入JSON文件,会被PHP当作可执行脚本解析触发语法错误;另外初版var_dump时将$editor->lieder嵌套在双引号字符串中,PHP会将其解析为纯文本字符串而非变量本身 - 缺少错误排查手段:遇到
json_decode返回null的情况,可直接调用json_last_error_msg()输出具体的解码错误原因,无需盲目排查代码
内容的提问来源于stack exchange,提问作者Captaincardbord
相关产品推荐
相关产品推荐

