英文:
Loop over JSON arrays in python
问题
我想要循环遍历我的JSON文件中的一个部分,并根据文件中的名称渲染几何图形。
```主.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,
"height": 40,
"color": {
"r": 255,
"g": 100,
"b": 0
}
},
"ellipse": {
"x": 200,
"y": 100,
"width": 400,
"height": 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”。是否有一种方法可以从几何图形中获取值?
英文:
I wanted to loop over a section in my JSON File and render the geometry based on their names in the File.
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
(a little simplified)
{
"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"
}
}
}
everytime i execute this code, ill get this error:
print(geo["rect"])
^^^^^^^^^^
TypeError: string indices must be integers, not 'str'
I tried it with indexes, like geo[0]
but it returned the first char of the string, "rect" -> "r"
Is there a way to get the values from the geometry?
答案1
得分: 1
一旦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"])
英文:
Once the json is loaded, it's represented as a dictionary in python. Just looping over a dictionary in python you get the keys from the dictionary, so so far your code is correct:
for geo in data["geometry"]:
if geo == "rect":
print("Rectangle")
If you want to grab the data belonging to this geometry, you could ask the original data
for geo in data["geometry"]:
if geo == "rect":
print("Rectangle", data["geometry"][geo])
Or better, use the items()
iterator that gives you the key and value directly as a tuple
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"]
答案2
得分: 1
根据您的数据,我会略微重构您的脚本。不要循环和比较字符串,而是可以使用 dict.get
来检查形状是否存在:
import json
with open('your_data.json', 'r') as f_in:
data = json.load(f_in)
geo = data['geometry']
# 绘制矩形:
if (shape := geo.get('rect')):
print('矩形', shape['x'], shape['y'])
# 绘制椭圆
if (shape := geo.get('ellipse')):
print('椭圆', shape['x'], shape['y'])
# ...
打印:
矩形 10 10
椭圆 200 100
英文:
Looking at your data I'd slightly restructure your script. Instead of looping and comparing strings you can use dict.get
and check if the shape is there:
import json
with open('your_data.json', 'r') as f_in:
data = json.load(f_in)
geo = data['geometry']
# draw rect:
if (shape:=geo.get('rect')):
print('Rect', shape['x'], shape['y'])
# draw ellipse
if (shape:=geo.get('ellipse')):
print('Ellipse', shape['x'], shape['y'])
# ...
Prints:
Rect 10 10
Ellipse 200 100
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论