2017-11-01 08:08:28 +00:00
|
|
|
"""JSON utility functions."""
|
|
|
|
import logging
|
|
|
|
from typing import Union, List, Dict
|
|
|
|
|
|
|
|
import json
|
|
|
|
|
|
|
|
from homeassistant.exceptions import HomeAssistantError
|
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2018-02-18 21:11:24 +00:00
|
|
|
|
2018-06-25 16:53:49 +00:00
|
|
|
class SerializationError(HomeAssistantError):
|
|
|
|
"""Error serializing the data to JSON."""
|
|
|
|
|
|
|
|
|
|
|
|
class WriteError(HomeAssistantError):
|
|
|
|
"""Error writing the data."""
|
|
|
|
|
|
|
|
|
2018-07-13 10:24:51 +00:00
|
|
|
def load_json(filename: str, default: Union[List, Dict, None] = None) \
|
2018-02-18 21:11:24 +00:00
|
|
|
-> Union[List, Dict]:
|
2017-11-01 08:08:28 +00:00
|
|
|
"""Load JSON data from a file and return as dict or list.
|
|
|
|
|
|
|
|
Defaults to returning empty dict if file is not found.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
with open(filename, encoding='utf-8') as fdesc:
|
|
|
|
return json.loads(fdesc.read())
|
|
|
|
except FileNotFoundError:
|
|
|
|
# This is not a fatal error
|
|
|
|
_LOGGER.debug('JSON file not found: %s', filename)
|
|
|
|
except ValueError as error:
|
|
|
|
_LOGGER.exception('Could not parse JSON content: %s', filename)
|
|
|
|
raise HomeAssistantError(error)
|
|
|
|
except OSError as error:
|
|
|
|
_LOGGER.exception('JSON file reading failed: %s', filename)
|
|
|
|
raise HomeAssistantError(error)
|
2018-07-13 10:24:51 +00:00
|
|
|
return {} if default is None else default
|
2017-11-01 08:08:28 +00:00
|
|
|
|
|
|
|
|
2018-03-01 03:31:38 +00:00
|
|
|
def save_json(filename: str, data: Union[List, Dict]):
|
2017-11-01 08:08:28 +00:00
|
|
|
"""Save JSON data to a file.
|
|
|
|
|
|
|
|
Returns True on success.
|
|
|
|
"""
|
|
|
|
try:
|
2018-07-13 10:24:51 +00:00
|
|
|
json_data = json.dumps(data, sort_keys=True, indent=4)
|
2017-11-01 08:08:28 +00:00
|
|
|
with open(filename, 'w', encoding='utf-8') as fdesc:
|
2018-07-13 10:24:51 +00:00
|
|
|
fdesc.write(json_data)
|
2017-11-01 08:08:28 +00:00
|
|
|
except TypeError as error:
|
|
|
|
_LOGGER.exception('Failed to serialize to JSON: %s',
|
|
|
|
filename)
|
2018-06-25 16:53:49 +00:00
|
|
|
raise SerializationError(error)
|
2017-11-01 08:08:28 +00:00
|
|
|
except OSError as error:
|
|
|
|
_LOGGER.exception('Saving JSON file failed: %s',
|
|
|
|
filename)
|
2018-06-25 16:53:49 +00:00
|
|
|
raise WriteError(error)
|