Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop over JSON arrays in python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading