diff options
| author | Eugene Triguba <eugenetriguba@gmail.com> | 2020-07-20 22:51:51 -0500 |
|---|---|---|
| committer | Eugene Triguba <eugenetriguba@gmail.com> | 2020-07-20 22:51:51 -0500 |
| commit | 65d4715b0b2b9974d95ac36271caa8e177bc98fa (patch) | |
| tree | 794b6338c8b0a654c4313a5da9713368fecfca7a /config_file/parsers/json_parser.py | |
| parent | Add toml and yaml parsers (diff) | |
| download | config-file-65d4715b0b2b9974d95ac36271caa8e177bc98fa.zip | |
Add BaseParser for all other parsers
This allows one implementation for all parsers,
with the parsers overriding it for a custom one
if needed for that parser.
Diffstat (limited to 'config_file/parsers/json_parser.py')
| -rw-r--r-- | config_file/parsers/json_parser.py | 127 |
1 files changed, 7 insertions, 120 deletions
diff --git a/config_file/parsers/json_parser.py b/config_file/parsers/json_parser.py index 237c0b5..5314cd7 100644 --- a/config_file/parsers/json_parser.py +++ b/config_file/parsers/json_parser.py @@ -1,128 +1,15 @@ import json -from config_file.exceptions import ParsingError -from config_file.nested_lookup import ( - get_occurrence_of_key, - nested_delete, - nested_lookup, - nested_update, -) -from config_file.parsers import AbstractParser, parse_value -from config_file.utils import split_on_dot +from .base_parser import BaseParser -class JsonParser(AbstractParser): - """ - The JsonParser allows use of json files with ConfigFile. The syntax it - supports is a bit more flexible than the IniParser. - - By default, the dot syntax is used. However, if you'd like to get/set/delete all - of a particular key, you can specify so with an optional parameter. - - Example: - - json = { - "key1": { - "key2": "foo", - "key1": "bar" - }, - "foo": "bar" - } - parser = JsonParser(json.dumps(json)) - parser.get('key1') - >>> { "key2": "foo", "key1": "bar" } - parser.get('key1.key2') - >>> "foo" - parser.get('key1', all=True) - >>> [{ "key2": "foo", "key1": "bar" }, "bar"] - """ - +class JsonParser(BaseParser): def __init__(self, file_contents: str): - """Reads in the file contents into the parser.""" - super().__init__(file_contents) - - def parse(self, file_contents: str): - try: - return json.loads(file_contents) - except json.decoder.JSONDecodeError as error: - raise ParsingError(error) - - def get(self, key: str, parse_types: bool = False, all: bool = False): - """ - Retrieve values using a dot syntax. - - :param key: The key to retrieve. e.g. 'foo.bar.boo' - - :param parse_types: Whether you'd like the type parsed into its native one. - - :param all: Specify whether you'd like to recursively receive - all values that match the given key. Returned as a list. - e.g. 'foo' would retrieve all values that have the key 'foo', anywhere - in the json. - - :return: the value of the given key - """ - if all: - result = nested_lookup(key, self.parsed_content) - elif "." in key: - split_keys = split_on_dot(key) - result = self.parsed_content - - key_causing_error = None - try: - for key in split_keys: - key_causing_error = key - result = result[key] - except TypeError: - raise ParsingError( - f"Cannot get {key} because {key_causing_error} " - "is not subscriptable." - ) - else: - result = self.parsed_content[key] - - return parse_value(result) if parse_types else result - - def set(self, key: str, value, all: bool = False): - if all: - nested_update(self.parsed_content, key, value, in_place=True) - elif "." in key: - indexes = split_on_dot(key) - indexes_length = len(indexes) - - ref = self.parsed_content - for index, key in enumerate(indexes): - if index == indexes_length - 1: - ref[key] = value - break - - ref = ref[key] - else: - self.parsed_content[key] = value - - return True - - def delete(self, key, all: bool = False): - if all: - nested_delete(self.parsed_content, key, in_place=True) - elif "." in key: - indexes = split_on_dot(key) - indexes_length = len(indexes) - - ref = self.parsed_content - for index, key in enumerate(indexes): - if index == indexes_length - 1: - del ref[key] - break - - ref = ref[key] - else: - del self.parsed_content[key] - - return True + super().__init__( + file_contents=file_contents, + module=json, + decode_error=json.decoder.JSONDecodeError, + ) def stringify(self) -> str: return json.dumps(self.parsed_content, indent=4) - - def has(self, search_key: str) -> bool: - return get_occurrence_of_key(self.parsed_content, key=search_key) > 0 |