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

解析含SortedDict的JSON格式字符串时遇JSONDecodeError问题求助

解决JSON解析SortedDict字符串的报错问题

问题重现

原始字符串:

sorted_dict = '{"state": SortedDict([("a", 1), ("b", 2), ("c", 3)])}'

尝试解析的代码:

mjl = json.loads(sorted_dict, object_pairs_hook=OrderedDict )

触发错误:

JSONDecodeError: Expecting value: line 1 column 11 (char 10)

报错原因

JSON语法仅支持标准数据类型(字符串、数字、对象、数组、布尔值、null),而SortedDict(...)是Python特有的类型表示,不属于合法的JSON值,json.loads无法识别该格式,因此抛出解析错误。

解决方案

方案1:生成标准JSON格式(推荐)

如果能控制该字符串的生成源头,先将SortedDict转换为普通字典再序列化,生成符合JSON规范的字符串:

from collections import SortedDict
import json

# 生成标准JSON字符串
original_sorted_dict = SortedDict([("a", 1), ("b", 2), ("c", 3)])
valid_json_str = json.dumps({"state": original_sorted_dict})
# 此时valid_json_str的值为 '{"state": {"a": 1, "b": 2, "c": 3}}'

# 解析为有序字典
from collections import OrderedDict
mjl = json.loads(valid_json_str, object_pairs_hook=OrderedDict)

这样即可正常解析得到有序字典。

方案2:解析Python字面量(适配现有字符串)

如果无法修改原始字符串,使用Python内置的ast.literal_eval解析该Python字面量格式的字符串:

from ast import literal_eval
from collections import OrderedDict, SortedDict

sorted_dict_str = '{"state": SortedDict([("a", 1), ("b", 2), ("c", 3)])}'
# 解析得到包含SortedDict实例的字典
parsed_data = literal_eval(sorted_dict_str)
# 如需转换为OrderedDict
state_ordered = OrderedDict(parsed_data["state"].items())

注意:ast.literal_eval仅能解析安全的Python字面量,禁止用于解析不可信来源的字符串,避免安全风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 14:55:27