diff --git a/homeassistant/components/shopping_list.py b/homeassistant/components/shopping_list.py index 416fdd3f6d0..2452188a889 100644 --- a/homeassistant/components/shopping_list.py +++ b/homeassistant/components/shopping_list.py @@ -1,8 +1,6 @@ """Component to manage a shopping list.""" import asyncio -import json import logging -import os import uuid import voluptuous as vol @@ -14,7 +12,7 @@ from homeassistant.components.http.data_validator import ( RequestDataValidator) from homeassistant.helpers import intent import homeassistant.helpers.config_validation as cv - +from homeassistant.util.json import load_json, save_json DOMAIN = 'shopping_list' DEPENDENCIES = ['http'] @@ -101,18 +99,13 @@ class ShoppingData: """Load items.""" def load(): """Load the items synchronously.""" - path = self.hass.config.path(PERSISTENCE) - if not os.path.isfile(path): - return [] - with open(path) as file: - return json.loads(file.read()) + return load_json(self.hass.config.path(PERSISTENCE), default=[]) self.items = yield from self.hass.async_add_job(load) def save(self): """Save the items.""" - with open(self.hass.config.path(PERSISTENCE), 'wt') as file: - file.write(json.dumps(self.items, sort_keys=True, indent=4)) + save_json(self.hass.config.path(PERSISTENCE), self.items) class AddItemIntent(intent.IntentHandler): diff --git a/homeassistant/util/json.py b/homeassistant/util/json.py index 810463260fd..7a326c34f15 100644 --- a/homeassistant/util/json.py +++ b/homeassistant/util/json.py @@ -8,8 +8,11 @@ from homeassistant.exceptions import HomeAssistantError _LOGGER = logging.getLogger(__name__) +_UNDEFINED = object() -def load_json(filename: str) -> Union[List, Dict]: + +def load_json(filename: str, default: Union[List, Dict] = _UNDEFINED) \ + -> Union[List, Dict]: """Load JSON data from a file and return as dict or list. Defaults to returning empty dict if file is not found. @@ -26,7 +29,7 @@ def load_json(filename: str) -> Union[List, Dict]: except OSError as error: _LOGGER.exception('JSON file reading failed: %s', filename) raise HomeAssistantError(error) - return {} # (also evaluates to False) + return {} if default is _UNDEFINED else default def save_json(filename: str, config: Union[List, Dict]):