'NoneType'对象从JSON文件读取时没有属性'read'

问题描述 投票:0回答:1

我正在为学校项目制作脚本,要求我收到一个JSON文件,该文件告诉我在图片中是否可以看到车牌。现在,代码将带有图像的POST发送到API,然后返回给我一个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不太熟悉,所以请您多加解释!

json python-3.7 attributeerror
1个回答
0
投票

事实证明,在重新阅读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())
© www.soinside.com 2019 - 2024. All rights reserved.