$line) { // 去除每行的首尾空白字符。 $line = trim($line); // 跳过空行。 if (empty($line)) { continue; } // 尝试解析当前行为 JSON。 $decoded = json_decode($line, true); // 检查解析是否成功。 if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { // 解析成功,添加到结果数组。 $result[] = $decoded; } else { // 解析失败,记录错误日志(可选)。 // 这里处理了截断的情况:如果某行不是有效 JSON,则跳过它。 // 通常最后一行可能因截断而无效,前面的有效行仍会被返回。 Log::warning("JSONL解析失败 - 行 " . ($lineNumber + 1) . ": " . $line); } } // 4. 返回解析结果。 // 即使没有成功解析任何行,也返回空数组而非 null,保持返回类型一致。 if (empty($result)) { Log::error('JSONL解析失败,未能提取任何有效数据: ' . $input); } return $result; } public static function jsonl_encode(array $input): string { $rows = []; foreach ($input as $key => $value) { $rows[] = json_encode($value, JSON_UNESCAPED_UNICODE); } return implode("\n", $rows); } }