JSONDecodeError: Expecting value: line 1 column 1 (char 0)错误总结

读取普通json文件时出现此错误

此处应为json文件的格式错误

  • 字典内键值应带双引号而不是单引号
  • 字典内最后一行应该不带逗号
dict = {
	"key1": 1,
	"key1": 2,
}

爬虫时出现该错误

爬虫时出现错误,主要集中在这一行代码中:

res = requests.get(url,headers=headers).json()

即为读取url中内容用json表示
错误信息如下(用的jupyter notebook):

Y:\Anaconda\envs\python36\lib\site-packages\requests\models.py in json(self, **kwargs)
    898                     # used.
    899                     pass
--> 900         return complexjson.loads(self.text, **kwargs)
    901 
    902     @property

Y:\Anaconda\envs\python36\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    352             parse_int is None and parse_float is None and
    353             parse_constant is None and object_pairs_hook is None and not kw):
--> 354         return _default_decoder.decode(s)
    355     if cls is None:
    356         cls = JSONDecoder

Y:\Anaconda\envs\python36\lib\json\decoder.py in decode(self, s, _w)
    337 
    338         """
--> 339         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    340         end = _w(s, end).end()
    341         if end != len(s):

Y:\Anaconda\envs\python36\lib\json\decoder.py in raw_decode(self, s, idx)
    355             obj, end = self.scan_once(s, idx)
    356         except StopIteration as err:
--> 357             raise JSONDecodeError("Expecting value", s, err.value) from None
    358         return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

如果url传输的是json文件,格式不可能出现问题(排除普通错误情况)
说明读取到内容不是json内容,有可能是返回的访问应答的错误信息error

此时应更新一下headers中的cookies,有可能是上次请求过久,cookies发生改变

更改后成功读取到json信息!!!

### 解决 Python Requests 库中的 `JSONDecodeError` 错误 当遇到 `requests.exceptions.JSONDecodeError: Extra data: line 1 column 6 (char 5)` 这样的错误时,通常意味着服务器返回的数据并非有效的 JSON 格式,或者存在多余的数据。以下是几种可能的原因及解决方案: #### 原因分析 - **响应体不是纯 JSON 数据**:如果响应中包含了其他字符或多个独立的 JSON 对象,则会引发此异常[^1]。 - **分隔符问题**:某些情况下,API 可能会在每次请求之间附加额外的内容,比如换行符或其他非 JSON 文本。 #### 处理方法一:验证并清理输入字符串 确保接收到的是干净且完整的 JSON 字符串再尝试解析: ```python import requests import json response = requests.get(url) try: clean_text = response.text.strip() if not clean_text.startswith("{") and not clean_text.endswith("}"): raise ValueError("Invalid JSON format") parsed_data = json.loads(clean_text) except Exception as e: print(f"Parsing failed with error {e}") ``` #### 方法二:处理多条记录的情况 对于包含多条 JSON 记录的情形,可采用逐行读取的方式进行解析,类似于使用 Pandas 的 `read_json()` 函数设置参数 `lines=True` 来加载流式的 JSON 文件[^2]: ```python for line in response.iter_lines(): try: item = json.loads(line.decode('utf-8')) process_item(item) # 自定义函数用于进一步操作每一条目 except json.JSONDecodeError as ex: logging.error(f"Failed to parse line due to {ex}. Skipping...") ``` #### 方法三:考虑 API 返回格式不一致的可能性 有时 Web API 设计不佳可能会导致不同条件下返回不同的内容结构;因此建议先通过浏览器开发者工具查看实际 HTTP 请求及其相应结果来确认预期格式是否稳定统一[^4].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值