Home Assistant Unofficial Reference 2024.12.1
util.py
Go to the documentation of this file.
1 """Helpers for RESTful API."""
2 
3 import logging
4 from typing import Any
5 
6 from jsonpath import jsonpath
7 
8 from homeassistant.util.json import json_loads
9 
10 _LOGGER = logging.getLogger(__name__)
11 
12 
14  value: str | None, json_attrs: list[str], json_attrs_path: str | None
15 ) -> dict[str, Any]:
16  """Parse JSON attributes."""
17  if not value:
18  _LOGGER.warning("Empty reply found when expecting JSON data")
19  return {}
20 
21  try:
22  json_dict = json_loads(value)
23  if json_attrs_path is not None:
24  json_dict = jsonpath(json_dict, json_attrs_path)
25  # jsonpath will always store the result in json_dict[0]
26  # so the next line happens to work exactly as needed to
27  # find the result
28  if isinstance(json_dict, list):
29  json_dict = json_dict[0]
30  if isinstance(json_dict, dict):
31  return {k: json_dict[k] for k in json_attrs if k in json_dict}
32 
33  _LOGGER.warning(
34  "JSON result was not a dictionary or list with 0th element a dictionary"
35  )
36  except ValueError:
37  _LOGGER.warning("REST result could not be parsed as JSON")
38  _LOGGER.debug("Erroneous JSON: %s", value)
39 
40  return {}
dict[str, Any] parse_json_attributes(str|None value, list[str] json_attrs, str|None json_attrs_path)
Definition: util.py:15