'NoneType' 对象在从 JSON 文件读取时没有属性 'read'
'NoneType' object has no attribute 'read' when reading from JSON file
我正在为一个学校项目制作脚本,该项目要求我收到一个 JSON 文件,告诉我车牌在图片中是否可见。现在代码将带有图像的 POST 发送到 API,然后在 return 中给我一个 JSON,JSON 数据被发送到文件"lastResponse.json."
给出错误的代码
with open('lastResponse.json', 'r+') as fp:
f = json.dump(r.json(), fp, sort_keys=True, indent=4) # Where the response data is sent to the JSON
data = json.load(f) # Line that triggers the error
print(data["results"]) # Debug code
print("------------------") # Debug code
print(data) # Debug code
# This statement just checks if a license plate is visible
if data["results"]["plate"] is None:
print("No car detected!")
else:
print("Car with plate number '" + data["results"]["plate"] + "' has been detected")
错误
Traceback (most recent call last):
File "DetectionFinished.py", line 19, in <module>
data = json.load(f)
File "/usr/lib/python3.7/json/__init__.py", line 293, in load
return loads(fp.read(),
AttributeError: 'NoneType' object has no attribute 'read'
我在 Python 方面不是很有经验,所以非常感谢您的解释!
事实证明,在重新阅读 API 的文档并使用他们的示例后,我能够解决我的问题
import requests
from pprint import pprint
regions = ['gb', 'it']
with open('/path/to/car.jpg', 'rb') as fp:
response = requests.post(
'https://api.platerecognizer.com/v1/plate-reader/',
data=dict(regions=regions), # Optional
files=dict(upload=fp),
headers={'Authorization': 'Token API_TOKEN'})
pprint(response.json())
我正在为一个学校项目制作脚本,该项目要求我收到一个 JSON 文件,告诉我车牌在图片中是否可见。现在代码将带有图像的 POST 发送到 API,然后在 return 中给我一个 JSON,JSON 数据被发送到文件"lastResponse.json."
给出错误的代码
with open('lastResponse.json', 'r+') as fp:
f = json.dump(r.json(), fp, sort_keys=True, indent=4) # Where the response data is sent to the JSON
data = json.load(f) # Line that triggers the error
print(data["results"]) # Debug code
print("------------------") # Debug code
print(data) # Debug code
# This statement just checks if a license plate is visible
if data["results"]["plate"] is None:
print("No car detected!")
else:
print("Car with plate number '" + data["results"]["plate"] + "' has been detected")
错误
Traceback (most recent call last):
File "DetectionFinished.py", line 19, in <module>
data = json.load(f)
File "/usr/lib/python3.7/json/__init__.py", line 293, in load
return loads(fp.read(),
AttributeError: 'NoneType' object has no attribute 'read'
我在 Python 方面不是很有经验,所以非常感谢您的解释!
事实证明,在重新阅读 API 的文档并使用他们的示例后,我能够解决我的问题
import requests
from pprint import pprint
regions = ['gb', 'it']
with open('/path/to/car.jpg', 'rb') as fp:
response = requests.post(
'https://api.platerecognizer.com/v1/plate-reader/',
data=dict(regions=regions), # Optional
files=dict(upload=fp),
headers={'Authorization': 'Token API_TOKEN'})
pprint(response.json())