如何解决如何从文件,字符串或其他来源不违反DRY原理中加载json
我经常需要将json加载到Python中,具体取决于我在管道中的位置,它可能是从文件名(光盘上的文件),打开的类似文件的对象(原始文件)加载的字符串,或者它可能已经从上一步加载了,在这种情况下,我将其传递了。
我有以下功能可以做到(可能会更健壮和完整,但您会明白):
import logging
import json
logger = logging.getLogger(__file__)
def load_json(source,*args,**kwargs):
""" Loads json,automatically detecting whether the input is a valid filename,a string containing json data,or a python dict already (in which case the result is returned directly).
That makes this function suitable for use in a pipeline where it's not clear whether data has been loaded yet,or
whether it's in a file or a raw string
:parameter source: The data source,which can be a string filename ending in *.json (json loaded from disc to
python dict),a string containing raw json data (json loaded from string to python dict),or any other
valid python object (passed through).
:parameter args,kwargs: Arguments passed through to json.load or json.loads,enabling use of custom encoders etc.
"""
# TODO allow source to be a file pointer too
if not isinstance(source,str):
logger.debug("Source is not a string,treating as raw data")
return source
elif source.endswith(".json"):
logger.debug("Detected source is *.json file,loading from %s",source)
with open(source) as f:
return json.load(f,**kwargs)
else:
logger.debug("Detected source is string containing json data,parsing...")
return json.loads(source,**kwargs)
我发现自己通过属于我和我的客户的几个库复制并粘贴了这个(或某些变体)。
为避免一次又一次重复,我可以为此在pypi上维护一个库,并将其用作我所有项目的依赖项。但是我真的不希望进行这项维护,除非那里还没有东西。
主要问题:
有人知道以这种(或非常相似的)方式处理json加载的现有的,易于导入的方法吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。