Files

62 lines
2.1 KiB
Python

import json
from typing import Any
import pandas as pd
from webapi.imports.connectors.errors import ConnectorError
from webapi.imports.connectors.registry import register_connector
from webapi.imports.connectors.tabular import FileConnector
@register_connector
class JsonConnector(FileConnector):
"""Nested objects are flattened to dotted column names
(`paciente.sexo`) into an object-dtype DataFrame, so JSON's own types
survive (`json_normalize` turns a sometimes-missing integer into floats)."""
kind = "json"
label = "JSON"
description = "Lista de registros; los objetos anidados se aplanan"
category = "file"
icon = "data_object"
extensions = ("json",)
option_names = ("record_path",)
def __init__(self, raw: bytes, *, record_path: str | None = None):
try:
data = json.loads(raw)
except Exception as exc:
raise ConnectorError(f"no se pudo leer el JSON: {exc}") from exc
if record_path:
try:
for key in record_path.split("."):
data = data[key]
except (KeyError, TypeError, IndexError) as exc:
raise ConnectorError(f"no se encontró record_path {record_path!r}: {exc}") from exc
if isinstance(data, dict):
data = data.get("data", [data])
if not isinstance(data, list) or not all(isinstance(record, dict) for record in data):
raise ConnectorError("el JSON debe dar una lista de objetos")
self._record_path = record_path
self._df = pd.DataFrame([_flatten(record) for record in data], dtype=object)
def _dataframe(self) -> pd.DataFrame:
return self._df
def metadata(self) -> dict:
return {"record_path": self._record_path}
def _flatten(record: dict[str, Any], prefix: str = "") -> dict[str, Any]:
flat: dict[str, Any] = {}
for key, value in record.items():
name = f"{prefix}{key}"
if isinstance(value, dict):
flat.update(_flatten(value, f"{name}."))
else:
flat[name] = value
return flat