read_json_with_comments

pull/10/head
root 2021-01-20 02:11:55 +00:00
parent 563bc921d8
commit ea39715305
1 changed files with 11 additions and 8 deletions

View File

@ -20,6 +20,16 @@ class AttrDict(dict):
self.__dict__ = self
def read_json_with_comments(json_path):
# fallback to json
with open(json_path, "r") as f:
input_str = f.read()
# handle comments
input_str = re.sub(r'\\\n', '', input_str)
input_str = re.sub(r'//.*\n', '\n', input_str)
data = json.loads(input_str)
return data
def load_config(config_path: str) -> AttrDict:
"""Load config files and discard comments
@ -33,14 +43,7 @@ def load_config(config_path: str) -> AttrDict:
with open(config_path, "r") as f:
data = yaml.safe_load(f)
else:
# fallback to json
with open(config_path, "r") as f:
input_str = f.read()
# handle comments
input_str = re.sub(r'\\\n', '', input_str)
input_str = re.sub(r'//.*\n', '\n', input_str)
data = json.loads(input_str)
data = read_json_with_comments(config_path)
config.update(data)
return config