You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解析含空格且报JSONDecodeError的Python列表?

解决方法

你的问题出在列表里每个字符串首尾多了一对多余的双引号,加上内部双引号未正确转义,导致JSON解析器无法识别合法的JSON结构。直接解析时,解析器会把开头的双引号当成字符串起始,遇到下一个双引号就判定字符串结束,后面的内容就成了“额外数据”,因此抛出错误。

解决步骤很直接:

  • 先给每个字符串去掉首尾的双引号(用strip('"')方法)
  • 再用json.loads解析处理后的字符串

具体代码实现

import json

# 注意:实际Python代码中,原列表的内部双引号需要转义,否则会报语法错误,正确写法如下
mylist=['"{  \\"score\\": \\"Really Good\\",  \\"text\\": \\"This is a text accompanying the score, level, and more.\\",  \\"level\\": \\"high level\\"}"',
        '"{  \\"score\\": \\"Not So Good\\",  \\"text\\": \\"This is a text accompanying the score, level, and more.\\",  \\"level\\": \\"high level\\"}"']

# 方式1:直接列表推导式提取字段
scores = [json.loads(item.strip('"'))["score"] for item in mylist]
texts = [json.loads(item.strip('"'))["text"] for item in mylist]
levels = [json.loads(item.strip('"'))["level"] for item in mylist]

# 方式2:先统一解析成字典,再提取字段(效率更高)
parsed_items = [json.loads(item.strip('"')) for item in mylist]
scores = [item["score"] for item in parsed_items]
texts = [item["text"] for item in parsed_items]
levels = [item["level"] for item in parsed_items]

print(scores)  # 输出: ['Really Good', 'Not So Good']

另外提醒:你提到的“key字段”在给出的JSON结构里不存在,只有score、text、level三个字段,若要访问key会报错,确认下是不是字段名写错了。

内容的提问来源于stack exchange,提问作者user321627

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 14:45:14