Python的json.dump()输出异常及json.loads解码报错求助
问题分析与解决
核心错误点
你的代码存在两个关键问题:
- 原始字符串不是合法JSON:JSON规范中,数组
[]只能存放值(字符串、数字、数组、对象等),不能存放键值对"test":0,键值对应使用对象{}包裹。你所有的["test": 0]写法都违反了JSON语法,同时字符串中还有多余的尾逗号(比如"Octagon": ["test": 0],}中的逗号),这直接导致json.loads解析失败。 - 直接dump字符串的错误行为:第一次使用
json.dump(dictio, file)时,dictio是字符串类型,json.dump会将其作为JSON的字符串值处理,因此输出会带有转义字符,这不是你需要的JSON结构。
修正后的解决方案
方案一:修正JSON字符串后解析转存
先修复原始字符串的语法错误,再进行解析和写入:
import json # 修正后的合法JSON字符串:将所有[]替换为{},移除多余尾逗号 dictio = """{"Forms": [{"Forms_2D": [{"Line": {"test": 0 },"Square": {"test": 0 },"Triangle": {"test": 0 },"Circle": {"test": 0},"Rectangle": {"test": 0},"Parallelogram": {"test": 0},"Rhombus": {"test": 0},"Trapezoid": {"test": 0},"Hexagon": {"test": 0},"Octagon": {"test": 0}}],"Forms_3D": [{"Cube": {"test": 0},"Pyramid": {"test": 0},"Cone": {"test": 0},"Cylinder": {"test": 0},"Sphere": {"test": 0},"Ball": {"test": 0},"Cuboid": {"test": 0}}]}],"Calculations": [{"Irrational": {"test": 0},"Not_a_Number": {"test": 0}}]}""" # 解析为Python对象后写入JSON文件 x = json.loads(dictio) with open("info.json", "w") as file: json.dump(x, file, indent=4, separators=(',', ': '))
方案二:直接使用Python字典(更推荐)
直接构造Python字典,再转存为JSON,从根源避免字符串语法错误:
import json # 直接构造Python字典结构 data = { "Forms": [ { "Forms_2D": [ { "Line": {"test": 0}, "Square": {"test": 0}, "Triangle": {"test": 0}, "Circle": {"test": 0}, "Rectangle": {"test": 0}, "Parallelogram": {"test": 0}, "Rhombus": {"test": 0}, "Trapezoid": {"test": 0}, "Hexagon": {"test": 0}, "Octagon": {"test": 0} } ], "Forms_3D": [ { "Cube": {"test": 0}, "Pyramid": {"test": 0}, "Cone": {"test": 0}, "Cylinder": {"test": 0}, "Sphere": {"test": 0}, "Ball": {"test": 0}, "Cuboid": {"test": 0} } ] } ], "Calculations": [ { "Irrational": {"test": 0}, "Not_a_Number": {"test": 0} } ] } with open("info.json", "w") as file: json.dump(data, file, indent=4, separators=(',', ': '))
最终效果
运行修正后的代码,info.json会生成格式正确的结构化JSON,示例片段如下:
{ "Forms": [ { "Forms_2D": [ { "Line": { "test": 0 }, "Square": { "test": 0 } } ] } ] }
内容的提问来源于stack exchange,提问作者Weqfreger
相关产品推荐
相关产品推荐

