我想循环遍历我的JSON文件中的一个部分,并根据文件中它们的名称呈现几何图形. main.py

import json

data = json.load(open('src/test.json'))

for geo in data["geometry"]:
    if geo == "rect":
       Geometry.rectangle(draw=pen, x=geo["x"], y=geo["y"], width=geo["width"],
                       height=geo["height"], rgb=geo["color"]

src/test.json(有点简化)

{
  "geometry": {
    "rect": {
      "x": 10,
      "y": 10,
      "width": 40,
      "heigth": 40,
      "color": {
        "r": 255,
        "g": 100,
        "b": 0
      }
    },
    "ellipse": {
      "x": 200,
      "y": 100,
      "width": 400,
      "heigth": 400,
      "color": {
        "r": 0,
        "g": 255,
        "b": 0
      }
    },
    "polygon": {
      "x": 200,
      "y": 100,
      "radius": 200,
      "sites": 8,
      "rotation": 90,
      "color": {
        "r": 0,
        "g": 255,
        "b": 0
      }
    },
    "text": {
      "x": 200,
      "y": 100,
      "size": 20,
      "text": "jklsajflksdjf",
      "words_per_line": 20,
      "id": "text_1",
      "align": "right",
      "color": {
        "r": 0,
        "g": 255,
        "b": 0
      },
      "font_style": "monospace"
    }
  }
}

每次执行此代码时,我都会收到以下错误:

print(geo["rect"])
          ^^^^^^^^^^
TypeError: string indices must be integers, not 'str'

我试着用索引,比如geo[0],但它返回了字符串的第一个字符,"rect" -> "r",有没有办法从几何体中获取这些值?

推荐答案

一旦加载了json,它就在python语言中表示为字典.只需循环遍历Python中的字典,就可以从字典中获得键,因此到目前为止,您的代码是正确的:

for geo in data["geometry"]:
    if geo == "rect":
        print("Rectangle")

如果要获取属于该几何的数据,可以询问原始数据

for geo in data["geometry"]:
    if geo == "rect":
        print("Rectangle", data["geometry"][geo])

或者更好的方法是使用items()迭代器,它直接将键和值作为元组提供

for geo_name, geo_data in data["geometry"].items():
    if geo_name == "rect":
        print("Rectangle", geo_data)
        Geometry.rectangle(draw=pen, x=geo_data["x"], y=geo_data["y"], width=geo_data["width"],
                           height=geo_data["height"], rgb=geo_data["color"]

Json相关问答推荐

如何在对象投影(*)上应用滤镜投影([?port==`eth1`])?

在解码的JSON哈希中搜索数组元素

创建Json嵌套文件 struct

在Ansible中从json中提取特定数据

在深度嵌套数组中使用布尔属性的jq-select

使用JQ合并JSON列表中的对象

如何在VB6中将字符串转换或解码为可读格式?

VSCode 为 python 文件添加标尺,但不为 C 文件添加标尺.为什么?

将=分隔值文件转换为:json文件

JOLT 转换仅过滤一个字段

将 JSON 字符串解析为 Kotlin Android 中的对象列表(MOSHI?)

Scala - 在构建 Json 时无法删除 Key -> value "{}" 大括号的双引号

在 Perl Mojolicious 中呈现 JSON 时防止转义字符

解析 JSON API 响应

从ruby中的json获取特定的键值

JSON RPC - 什么是id?

如何使用 Jackson 重命名 JSON 序列化中的根键

如何在 Perl 中将简单的哈希转换为 json?

如何转换为 D3 的 JSON 格式?

Newtonsoft 对象 → 获取 JSON 字符串