Skip to content
Advertisement

Pull values from the JSON in order – first all the first character, then all the seconds and etc

This is JSON:

    "y": {
        "titleOne": {
            "a": [{
                    "ss": "one"
                }, {
                    "ss": "two"
                }
            ]
        },
        "titleTwo": {
            "a": [{
                    "ss": "one"
                }, {
                    "ss": "two"
                }, {
                    "ss": "thee"
                }
            ]
        },
        ..........

This is my current code:

for i in y:
   for c in y[i]["a"]:
      print(c["ss"])

This code will simply print all values in order:

one
two
one
two
three

but I need that loop will get the first value from each section and will return

one
one
two
two
three

Advertisement

Answer

Maybe something like this:

y = {"titleOne": {"a": [{"ss": "one"}, {"ss": "two"}]},
     "titleTwo": {"a": [{"ss": "one"}, {"ss": "two"}, {"ss": "three"}]}}

#check the max depth you can go to
depth = max(len(y[title]["a"]) for title in y)
for i in range(depth):
    for title in y:
        if len(y[title]["a"])>i:
            print(y[title]["a"][i]["ss"])

one
one
two
two
three
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement