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

PHP中如何解析API响应内的多个独立JSON对象

解析无逗号分隔的多JSON对象方案
  • 按行拆分逐个解析
    观察返回内容,每个JSON对象单独占一行,直接按换行符分割原始响应字符串,再对每一行单独调用json_decode:

    // $response 为API返回的原始文本
    $lines = explode("\n", trim($response));
    $parsedData = [];
    foreach ($lines as $line) {
        $line = trim($line);
        if (!empty($line)) {
            $obj = json_decode($line, true);
            if ($obj !== null) {
                $parsedData[] = $obj;
            }
        }
    }
    // $parsedData 中存储所有解析后的JSON对象
    
  • 转换为标准JSON数组解析
    如果JSON对象不严格按行分布,可以给整个响应文本前后添加[和],再将}{替换为},{,把内容转换成标准JSON数组后解析:

    $fixedContent = '[' . str_replace('}{', '},{', trim($response)) . ']';
    $parsedData = json_decode($fixedContent, true);
    // 解析成功后 $parsedData 即为包含所有对象的数组
    

注意:第二种方法需确保JSON对象内部的字符串值中不会出现}{组合,否则会破坏结构。若API返回的每个JSON对象都是独立成行的,第一种方法更可靠。

内容的提问来源于stack exchange,提问作者Tanvir Hasan Emon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 21:05:32