|
| 1 | +import json |
| 2 | +import re |
1 | 3 | from datetime import datetime |
2 | 4 | from functools import lru_cache |
3 | | -from typing import Union |
| 5 | +from typing import Any, Dict, List, Union |
4 | 6 |
|
5 | 7 | import pydantic |
6 | 8 |
|
| 9 | +_CONCATENATED_JSON = re.compile(r"(?<=\})\s*(?=\{)") |
| 10 | + |
7 | 11 |
|
8 | 12 | @lru_cache(maxsize=1) |
9 | 13 | def is_pydantic_2() -> bool: |
@@ -41,3 +45,28 @@ def iso_to_date_time(iso_date: Union[datetime, str, None]) -> Union[datetime, No |
41 | 45 | reduce = len(split[1]) - 6 |
42 | 46 | reduced = f"{split[0]}.{split[1][:-reduce]}Z" |
43 | 47 | return datetime.strptime(reduced, "%Y-%m-%dT%H:%M:%S.%fZ") |
| 48 | + |
| 49 | + |
| 50 | +def parse_task_documents(raw_documents: str) -> List[Dict[str, Any]]: |
| 51 | + """Parse the payload returned by ``GET /tasks/{uid}/documents``. |
| 52 | +
|
| 53 | + The endpoint may return a JSON array, a single JSON object, NDJSON, or |
| 54 | + several JSON objects concatenated without a separator. This normalizes all |
| 55 | + of those formats into a list of documents. |
| 56 | + """ |
| 57 | + payload = raw_documents.strip() |
| 58 | + if not payload: |
| 59 | + return [] |
| 60 | + |
| 61 | + try: |
| 62 | + parsed = json.loads(payload) |
| 63 | + except json.JSONDecodeError: |
| 64 | + documents: List[Dict[str, Any]] = [] |
| 65 | + for line in payload.splitlines(): |
| 66 | + for chunk in _CONCATENATED_JSON.split(line): |
| 67 | + stripped = chunk.strip() |
| 68 | + if stripped: |
| 69 | + documents.append(json.loads(stripped)) |
| 70 | + return documents |
| 71 | + |
| 72 | + return parsed if isinstance(parsed, list) else [parsed] |
0 commit comments