无法解析JSON字符串并获取label字段值,报错JSONDecodeError
JSON解析错误与修复方案
你遇到的问题出在JSON字符串格式错误,以及后续的数据访问方式不对,具体问题和修复方法如下:
你的错误代码
import json json_str = '{mechanisms": {"label": "Mechanismen", "type": "MechSections"}}' data = json.loads(json_str) print(data['mechanisms'][0]['label'])
报错内容
Traceback (most recent call last): File "D:/PyCharm/Projekte/Vivia_Medikamente/main.py", line 5, in <module> data = json.loads(json_str) File "C:\Users\Bennett\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads return _default_decoder.decode(s) File "C:\Users\Bennett\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\Bennett\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 353, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
问题根源
- JSON格式不合法:
- 第一个键
mechanisms没加双引号,JSON语法要求所有属性名必须用双引号包裹。 - 字符串里的
"是HTML转义后的双引号,得换成实际的"才能被JSON解析器识别。
- 第一个键
- 数据访问错误:
mechanisms对应的是一个字典对象,不是数组,不能用[0]这种索引去访问。
修复后的代码
import json # 修正JSON字符串的格式问题 json_str = '{"mechanisms": {"label": "Mechanismen", "type": "MechSections"}}' data = json.loads(json_str) # 直接通过字典键访问label字段 print(data['mechanisms']['label'])
运行这段代码就能输出Mechanismen。
内容的提问来源于stack exchange,提问作者Bennett Minor
相关产品推荐
相关产品推荐

