Add return type to json_loads (#85672)
* Add JSON type definitions * Sample use * Keep mutable for a follo-up PR (avoid dead code) * Use list/dict * Remove JsonObjectType * Remove reference to Union * Cleanup * Improve rest * Rename json_dict => json_data * Add docstring * Add type hint to json_loads * Add cast * Move type alias to json helpers * Cleanup * Create and use json_loads_object * Make error more explicit and add tests * Use JsonObjectType in conversation * Remove quotes
This commit is contained in:
parent
20b60d57f2
commit
a202588fd2
11 changed files with 70 additions and 28 deletions
|
@ -1,4 +1,5 @@
|
|||
"""Helpers to help with encoding Home Assistant objects in JSON."""
|
||||
from collections.abc import Callable
|
||||
import datetime
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
@ -6,6 +7,13 @@ from typing import Any, Final
|
|||
|
||||
import orjson
|
||||
|
||||
JsonValueType = (
|
||||
dict[str, "JsonValueType"] | list["JsonValueType"] | str | int | float | bool | None
|
||||
)
|
||||
"""Any data that can be returned by the standard JSON deserializing process."""
|
||||
JsonObjectType = dict[str, JsonValueType]
|
||||
"""Dictionary that can be returned by the standard JSON deserializing process."""
|
||||
|
||||
JSON_ENCODE_EXCEPTIONS = (TypeError, ValueError)
|
||||
JSON_DECODE_EXCEPTIONS = (orjson.JSONDecodeError,)
|
||||
|
||||
|
@ -132,7 +140,18 @@ def json_dumps_sorted(data: Any) -> str:
|
|||
).decode("utf-8")
|
||||
|
||||
|
||||
json_loads: Callable[[bytes | bytearray | memoryview | str], JsonValueType]
|
||||
json_loads = orjson.loads
|
||||
"""Parse JSON data."""
|
||||
|
||||
|
||||
def json_loads_object(__obj: bytes | bytearray | memoryview | str) -> JsonObjectType:
|
||||
"""Parse JSON data and ensure result is a dictionary."""
|
||||
value: JsonValueType = json_loads(__obj)
|
||||
# Avoid isinstance overhead as we are not interested in dict subclasses
|
||||
if type(value) is dict: # pylint: disable=unidiomatic-typecheck
|
||||
return value
|
||||
raise ValueError(f"Expected JSON to be parsed as a dict got {type(value)}")
|
||||
|
||||
|
||||
JSON_DUMP: Final = json_dumps
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue