错误json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)的解决记录

出问题的代码部分是这样的,
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201019202700912.png#pic_center在这里插入图片描述

这是因为返回状态码为200,但是返回内容为空导致的。
我的判断条件是response.status_code == 200

import requests
import sys
struct = {}
#执行API调用并存储响应
url = 'http://api.gihub.com/search/repositories?q=language:python&sort=stars'
print("status code",requests.get(url).status_code)
#将API响应存储在一个变量中
try:
    response = requests.get(url,timout = 3)
    #response.status_code == 200 
    if response.content:
        response_dict = response.json()
        print("total repositories:",response_dict['total_count'])
        #探索有关仓库的信息
        repo_dicts = response_dict['items']
        print("repositories returned:",len(repo_dicts))
        #研究第一个仓库
        repo_dict = repo_dicts[0]
        print("\nkeys:",len(repo_dict))
        for key in sorted(repo_dict.keys()):
            print(key)
except:
    print("ok")

不要直接判断返回状态,因为返回为200的时候也可能内容为空,就会报错,判断返回内容是否None。httpcode200也可能返回内容None

参考:解决json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)问题
### 解决 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]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值