gateway/modules/services/serviceExtraction/formats/json_extractor.py

31 lines
993 B
Python

from typing import Any, Dict, List
import json
from modules.datamodels.datamodelExtraction import ContentPart
from ..utils import makeId
from ..subRegistry import Extractor
class JsonExtractor(Extractor):
def detect(self, fileName: str, mimeType: str, headBytes: bytes) -> bool:
return mimeType == "application/json" or (fileName or "").lower().endswith(".json")
def extract(self, fileBytes: bytes, context: Dict[str, Any]) -> List[ContentPart]:
mimeType = context.get("mimeType") or "application/json"
text = fileBytes.decode("utf-8", errors="replace")
# verify JSON is well-formed; fall back to text if not
try:
json.loads(text)
except Exception:
pass
return [ContentPart(
id=makeId(),
parentId=None,
label="main",
typeGroup="structure",
mimeType=mimeType,
data=text,
metadata={"size": len(fileBytes)}
)]