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?
2
Answers
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:
If you want to grab the data belonging to this geometry, you could ask the original data
Or better, use the
items()
iterator that gives you the key and value directly as a tupleLooking 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:Prints: