hass-core/homeassistant/util/json.py

122 lines
3.6 KiB
Python
Raw Normal View History

"""JSON utility functions."""
2021-03-17 21:46:07 +01:00
from __future__ import annotations
from collections import deque
from collections.abc import Callable
import json
import logging
from typing import Any
from homeassistant.core import Event, State
from homeassistant.exceptions import HomeAssistantError
2021-11-11 00:19:56 -06:00
from .file import write_utf8_file
_LOGGER = logging.getLogger(__name__)
class SerializationError(HomeAssistantError):
"""Error serializing the data to JSON."""
class WriteError(HomeAssistantError):
"""Error writing the data."""
2021-03-17 21:46:07 +01:00
def load_json(filename: str, default: list | dict | None = None) -> list | dict:
"""Load JSON data from a file and return as dict or list.
Defaults to returning empty dict if file is not found.
"""
try:
2019-07-31 12:25:30 -07:00
with open(filename, encoding="utf-8") as fdesc:
return json.loads(fdesc.read()) # type: ignore
except FileNotFoundError:
# This is not a fatal error
2019-07-31 12:25:30 -07:00
_LOGGER.debug("JSON file not found: %s", filename)
except ValueError as error:
2019-07-31 12:25:30 -07:00
_LOGGER.exception("Could not parse JSON content: %s", filename)
raise HomeAssistantError(error) from error
except OSError as error:
2019-07-31 12:25:30 -07:00
_LOGGER.exception("JSON file reading failed: %s", filename)
raise HomeAssistantError(error) from error
return {} if default is None else default
2019-07-31 12:25:30 -07:00
def save_json(
filename: str,
2021-03-17 21:46:07 +01:00
data: list | dict,
2019-07-31 12:25:30 -07:00
private: bool = False,
*,
2021-03-17 21:46:07 +01:00
encoder: type[json.JSONEncoder] | None = None,
2019-07-31 12:25:30 -07:00
) -> None:
"""Save JSON data to a file.
Returns True on success.
"""
try:
json_data = json.dumps(data, indent=4, cls=encoder)
except TypeError as error:
msg = f"Failed to serialize to JSON: {filename}. Bad data at {format_unserializable_data(find_paths_unserializable_data(data))}"
_LOGGER.error(msg)
raise SerializationError(msg) from error
2021-11-11 00:19:56 -06:00
write_utf8_file(filename, json_data, private)
2021-03-17 21:46:07 +01:00
def format_unserializable_data(data: dict[str, Any]) -> str:
"""Format output of find_paths in a friendly way.
Format is comma separated: <path>=<value>(<type>)
"""
return ", ".join(f"{path}={value}({type(value)}" for path, value in data.items())
def find_paths_unserializable_data(
bad_data: Any, *, dump: Callable[[Any], str] = json.dumps
2021-03-17 21:46:07 +01:00
) -> dict[str, Any]:
"""Find the paths to unserializable data.
This method is slow! Only use for error handling.
"""
to_process = deque([(bad_data, "$")])
invalid = {}
while to_process:
obj, obj_path = to_process.popleft()
try:
dump(obj)
2020-02-18 16:06:13 -08:00
continue
except (ValueError, TypeError):
2020-02-18 16:06:13 -08:00
pass
# We convert objects with as_dict to their dict values so we can find bad data inside it
if hasattr(obj, "as_dict"):
desc = obj.__class__.__name__
if isinstance(obj, State):
desc += f": {obj.entity_id}"
elif isinstance(obj, Event):
desc += f": {obj.event_type}"
obj_path += f"({desc})"
obj = obj.as_dict()
if isinstance(obj, dict):
for key, value in obj.items():
try:
# Is key valid?
dump({key: None})
except TypeError:
invalid[f"{obj_path}<key: {key}>"] = key
else:
# Process value
to_process.append((value, f"{obj_path}.{key}"))
elif isinstance(obj, list):
for idx, value in enumerate(obj):
to_process.append((value, f"{obj_path}[{idx}]"))
2020-02-18 16:06:13 -08:00
else:
invalid[obj_path] = obj
return invalid