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

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

代码描述

学习Python的数据存储时,接触到JSON格式。
同时使用到函数json.dump()和json.load()进行数据写入和读取。

import json

filename = 'username.json'
try:
    with open(filename) as f_obj:
        username = json.load(f_obj)
except FileNotFoundError:
    username = input("What is your name?")
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
        print('Remember you! ' + username + '!')
else:
    print("Welcome back, " + username + '!')

注:代码源于《Python编程从入门到实践》

错误(只截了最下面一行错误Traceback)

错误traceback

原因与解决方法

有另一个.py 文件中先前创建并使用过 username.json 文件,产生了冲突。
把代码中的filename取个其他的名字即可。

学习尚浅,记录理解有限,希望指正。

### 解决 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、付费专栏及课程。

余额充值