gpt4 book ai didi

Python加载json帮助器方法不起作用

转载 作者:行者123 更新时间:2023-11-30 22:15:59 24 4
gpt4 key购买 nike

我定义了一个辅助方法来从字符串或文件加载 json,如下所示:

def get_json_from_string_or_file(obj):
if type(obj) is str:
return json.loads(obj)
return json.load(obj)

当我尝试使用文件时,load 调用失败,并出现以下异常:

File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 291, in load
**kw)
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

我已经三次检查了我的 json 文件,它绝对不是空的,它只有一个简单的 foo bar 键值映射。

另外,我将 json 文件输入到方法中,如下所示:

os.path.join(os.path.dirname(__file__), "..", "test.json")

知道这里发生了什么吗?

编辑:我将我的帮助程序方法更改为以下内容,以修复答案和评论中提到的错误,但它仍然不起作用,当我传递一个已经打开的文件时,我遇到了相同的错误。

def get_json_from_file(_file):
if type(_file) is str:
with open(_file) as json_file:
return json.load(json_file)
return json.load(_file)

编辑#2:我发现了问题!如果您连续两次对打开的文件调用 json.load ,则会出现此错误。事实证明,我的应用程序的另一部分已经打开了该文件。

这里是一些复制代码:

with open("/test.json") as f:
json.load(f)
json.load(f)

最佳答案

以下代码有效。

import os
import json

def get_json_from_string_or_file(obj):
if type(obj) is str:
return json.loads(obj)
return json.load(obj)

filename = os.path.join(os.path.dirname(__file__), "..", "test.json")
with open(filename, 'r') as f:
result = get_json_from_string_or_file(f)
print(result)
当我将文件名传递给函数时,会重现

ValueError:无法解码任何 JSON 对象,例如 get_json_from_string_or_file(filename)

<小时/>

第二版

import os
import json

def get_json_from_file(_file):
if type(_file) is str: # <-- unnecessary if
with open(_file) as json_file:
return json.load(json_file)
return json.load(_file)

filename = os.path.join(os.path.dirname(__file__), "..", "test.json")
result = get_json_from_file(filename)

print(result)
# python2: {u'foo': u'bar'}
# python3: {'foo': 'bar'}

关于Python加载json帮助器方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50092608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com