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

Python中json.loads()报未终止字符串错误,JSON校验有效却无法加载?

问题原因与解决方案

核心问题

你遇到的错误根源有两个:

  1. JSON顶层结构不合法:你的JSON内容是两个独立对象用逗号直接并列,但JSON规范要求顶层结构只能是单个对象({})或数组([]),不能是多个对象直接拼接。
  2. 外层多余的双引号:整个JSON内容被包裹在一对双引号中,这会让json.loads()把它当作普通字符串解析,而内部的转义双引号会导致解析时出现“字符串未终止”的错误。

解决步骤

1. 修正JSON结构

把两个对象包裹在数组中(添加首尾的[]),同时去掉外层的双引号,得到合法的JSON:

[{"question": "What artist released the hit song 'Hello' in 2015?", "answers": ["Taylor Swift", "Katy Perry", "$Adele", "Lady Gaga"], "topic": "Music in the 2010's"}, {"question": "Who is the featured artist on the song 'Despacito' by Luis Fonsi?", "answers": ["Enrique Iglesias", "Maluma", "$Justin Bieber", "Pitbull"], "topic": "Music in the 2010's"}]

2. 对应的Python代码

在Python中使用时,对应的字符串写法如下:

import json

valid_json_str = '[{"question": "What artist released the hit song \'Hello\' in 2015?", "answers": ["Taylor Swift", "Katy Perry", "$Adele", "Lady Gaga"], "topic": "Music in the 2010\'s"}, {"question": "Who is the featured artist on the song \'Despacito\' by Luis Fonsi?", "answers": ["Enrique Iglesias", "Maluma", "$Justin Bieber", "Pitbull"], "topic": "Music in the 2010\'s"}]'

data = json.loads(valid_json_str)
print(data)

关于jsonchecker.com显示有效的说明

部分在线JSON校验工具会对非标准JSON做兼容处理(比如自动将多个并列对象转为数组),但Python的json模块严格遵循JSON官方规范,不会做这类容错处理,因此出现了工具显示有效但代码报错的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 04:00:14