27 lines
922 B
Python
27 lines
922 B
Python
|
|
"""Подготовка структур из JSON к записи в PostgreSQL jsonb."""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import math
|
||
|
|
from typing import Any
|
||
|
|
|
||
|
|
|
||
|
|
def sanitize_for_jsonb(obj: Any) -> Any:
|
||
|
|
"""
|
||
|
|
- float NaN / ±Inf → None (иначе json.dumps даёт невалидный JSON для PG / сюрпризы при записи).
|
||
|
|
- Символ NUL в строках убрать (PostgreSQL text/jsonb NUL в строке не принимает).
|
||
|
|
"""
|
||
|
|
if isinstance(obj, float):
|
||
|
|
if math.isnan(obj) or math.isinf(obj):
|
||
|
|
return None
|
||
|
|
return obj
|
||
|
|
if isinstance(obj, str):
|
||
|
|
if "\x00" not in obj:
|
||
|
|
return obj
|
||
|
|
return obj.replace("\x00", "")
|
||
|
|
if isinstance(obj, dict):
|
||
|
|
return {k: sanitize_for_jsonb(v) for k, v in obj.items()}
|
||
|
|
if isinstance(obj, list):
|
||
|
|
return [sanitize_for_jsonb(x) for x in obj]
|
||
|
|
return obj
|