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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 05:10:08