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

PHP解析多层嵌套JSON时如何获取innererror下的message值

错误原因

代码取值路径和实际JSON结构不匹配,存在两处错误:

  • 根节点下没有直接的innererror键,innererror是外层odata.error键的子节点
  • innererror是关联数组结构,不存在索引为0的元素,多余的[0]下标会导致取值失败
修复后代码
$json = '{
  "odata.error":{
        "code":"",
        "message":{
            "lang":"en-US",
            "value":"The request is invalid."
            },
        "innererror":{
            "message":"entity : An error has occurred.",
            "type":"",
            "stacktrace":""
            }
  }
}';
$json_data = json_decode($json,true);

// 按照JSON实际嵌套层级逐层取值
$targetMessage = $json_data['odata.error']['innererror']['message'];

echo $targetMessage;

执行上述代码会直接输出目标值:entity : An error has occurred.

排查技巧
  • 不确定解析后的数组结构时,可直接用var_dump($json_data)打印完整结构,对照层级匹配键名
  • 解析JSON后建议先通过json_last_error() === JSON_ERROR_NONE判断是否解析成功,排除JSON格式错误导致的取值异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 05:57:17