解决json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

前言

        作者在读取json文件的时候出现上述报错,起初以为是自己json文件有问题,但借助在线工具查看后发现没问题,就卡住了,在debug的过程中发现了json文件读取的一个小坑,在此分享一下

解决过程

原代码

with open(annotations_file) as f:
    lenth = len(json.load(f)["annotations"])
    #print(json.load(f)["annotations"])
    if is_train:
        data = json.load(f)["annotations"][0:int(lenth*0.8)]
    else:
        data = json.load(f)["annotations"][int(lenth*0.8):]

乍一看这个代码没有什么问题,但是作者发现lenth可以拿到数据,但是data执行时会报错,这就很奇怪,两行代码关于json文件读取的操作是一致的,为什么就是不行,后边作者加了print发现也会报错,因此得到结论,在一个with里不能加载两次

修改后代码

with open(annotations_file) as f:
    data = json.load(f)["annotations"]
    length = len(data)
    if is_train:
        data = data[:int(length * 0.8)]
    else:
        data = data[int(length * 0.8):]

问题解决

### 解决 Python 中 `JSONDecodeError: Expecting value` 错误 当遇到 `json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)` 错误时,这通常意味着尝试解析的内容为空或不是有效的 JSON 字符串。为了妥善处理这种情况并防止程序崩溃,可以采取以下措施: #### 添加请求验证逻辑 在从 API 获取数据后,应该先检查 HTTP 响应的状态码以及返回的数据是否有效。如果一切正常,则继续执行 JSON 解析;否则给出相应的提示。 ```python import json import requests response = requests.get('https://api.example.com/data') if response.status_code == 200 and response.text.strip(): try: data = json.loads(response.text) # 处理成功加载的data... except json.JSONDecodeError as e: print(f"Error decoding JSON: {e}") else: print("Error: Received empty or invalid response") ``` 这段代码首先确认服务器端返回的是成功的状态码(即 200),并且响应体不为空字符串之后再做进一步操作[^1]。 #### 使用上下文管理器读取文件 如果是从本地文件中读取 JSON 数据而遇到了同样的问题,建议使用带有异常捕获机制的方法来打开和关闭文件流,并同样加入对文件内容的有效性判断。 ```python try: with open('file.json', 'r') as f: content = f.read().strip() if not content: raise ValueError("File is empty.") data = json.loads(content) except FileNotFoundError: print("The specified file does not exist.") except ValueError as ve: print(ve) except json.JSONDecodeError as je: print(f"There was an error parsing the JSON from file: {je}") ``` 通过这种方式可以在发现任何潜在的问题之前就对其进行拦截,从而提高代码健壮性和用户体验[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值