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.py (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?
>Solution :
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"]