def json_config(jfile, jobj_hook=None, jwrite_obj=None, jappend=None):
"""
Simple interface to json library functions. Reads JSON data into object
dictionary or appends json data to existing file.
See the json library documentation for more info.
`json <https://docs.python.org/3/library/json.html>`_
Parameters
----------
jfile : str
json file path.
jobj_hook : function (default: None)
Decoder. If None, decodes to dict.
jwrite_obj : obj (default: None)
Obj to write to existing json file ``jfile``.
Evaluated before ``jappend``.
jappend : obj (default: None)
New data to append to existing json file ``jfile``.
"""
# write if file does not exist.
if jwrite_obj is not None:
# Write `jwrite_obj` if file does not exist.
if not any([os.path.isfile(jfile),
os.path.isfile(os.path.abspath(jfile)),
jwrite_obj]):
print('writing `jwrite_obj` to new json `jfile`.')
with open(jfile, 'w') as f:
json.dump(jwrite_obj, f, sort_keys=True, ensure_ascii=False)
else:
print('No json in path provided.')
return
if jappend is not None:
with open(jfile, 'r+') as f:
json_dict = json.load(f, object_hook=None)
json_dict.update(jappend)
f.seek(0)
f.truncate() # todo: Improve to only truncate if needed.
# print(len(f.readlines()))
json.dump(json_dict, f, sort_keys=True, indent=4)
f.close()
return
with open(jfile) as f:
if jobj_hook is not None:
return json.load(f, object_hook=jobj_hook)
return json.load(f)
评论列表
文章目录