Python遍历JSON的geometry对象报错TypeError,如何获取对应数据?
问题分析与解决
错误原因
data["geometry"]是一个字典对象,直接用for geo in data["geometry"]循环时,geo拿到的是字典的键(比如"rect"、"ellipse"这类字符串),而非对应的参数对象。所以你尝试geo["x"]时,本质是对字符串使用字符串索引,自然触发TypeError。
正确遍历方式
使用字典的items()方法,同时获取图形名称(键)和对应的参数数据(值),就能正确拿到每个图形的配置信息:
import json data = json.load(open('src/test.json')) # 遍历geometry的键值对:图形名称 + 对应参数数据 for geo_name, geo_data in data["geometry"].items(): if geo_name == "rect": # 注意:JSON里的"heigth"是拼写错误,建议改成"height",这里做兼容处理 Geometry.rectangle( draw=pen, x=geo_data["x"], y=geo_data["y"], width=geo_data["width"], height=geo_data.get("height") or geo_data["heigth"], rgb=(geo_data["color"]["r"], geo_data["color"]["g"], geo_data["color"]["b"]) ) elif geo_name == "ellipse": Geometry.ellipse( draw=pen, x=geo_data["x"], y=geo_data["y"], width=geo_data["width"], height=geo_data.get("height") or geo_data["heigth"], rgb=(geo_data["color"]["r"], geo_data["color"]["g"], geo_data["color"]["b"]) ) elif geo_name == "polygon": Geometry.polygon( draw=pen, x=geo_data["x"], y=geo_data["y"], radius=geo_data["radius"], sites=geo_data["sites"], rotation=geo_data["rotation"], rgb=(geo_data["color"]["r"], geo_data["color"]["g"], geo_data["color"]["b"]) ) elif geo_name == "text": Geometry.text( draw=pen, x=geo_data["x"], y=geo_data["y"], size=geo_data["size"], text=geo_data["text"], words_per_line=geo_data["words_per_line"], align=geo_data["align"], font_style=geo_data["font_style"], rgb=(geo_data["color"]["r"], geo_data["color"]["g"], geo_data["color"]["b"]) )
额外注意事项
- JSON中的
heigth是拼写错误,建议统一修正为height,避免后续取值异常。 - 调用
Geometry类方法时,需确保参数格式匹配,比如rgb参数需要传入(r,g,b)元组,而非原字典中的color对象。 - 原代码中
Geometry.rectangle的调用缺少闭合括号,已在修正代码中补全。
内容的提问来源于stack exchange,提问作者mxritz
相关产品推荐
相关产品推荐

