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
相关产品推荐
相关产品推荐

