skip to Main Content

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


  1. 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"]
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search