我想循环遍历我的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"
,有没有办法从几何体中获取这些值?