integration layer; merge work on indicators from forks with existing ingestion pipeline
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
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"could not parse 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"record_path {record_path!r} not found: {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("JSON source must resolve to a list of objects")
|
||||
|
||||
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
|
||||
Reference in New Issue
Block a user