Home > Back-end >  Python JSON parsing does not find key or value I want
Python JSON parsing does not find key or value I want

Time:12-25

I have a code that recursively parses through a rather large JSON. I have recreated what I need with a small JSON here and the problem persists.

{
    "one": "one",
    "two": {
        "three": "three",
        "four": [{
            "five": {
                "six": "six"
            }
        }]
    }
}

and here is my Python

json_file_path = r"\filepathto\testing.json"
j = json.load(c.open(json_file_path, 'r', 'utf-8-sig'))
def dict_opener(j):
    if isinstance(j, dict):
        for key, value in j.items():
            if isinstance(value, list):
                list_opener(j)
            if isinstance(value, dict) and key == "five":
                print("found")
            elif isinstance(value, dict):
                dict_opener(value)

def list_opener(j):
    for i in j:
        if isinstance(i, list):
            list_opener(i)
        elif isinstance(i, dict):
            dict_opener(i)


dict_opener(j)

This works to get many of the JSON elements (for instance, doing a key like three works fine), but doesn't work when I need the five element. Right now I'm just trying to get everything inside five, so I don't care how it's formatted or anything. I'm also aware that j["two"]["four"][0]["five"] works but the JSON will be constantly changing so I don't want to do that.

The function runs with no errors but gives no output (not even "found") so I don't know why it's happening. I'm pretty new with JSONs so maybe this is a stupid question but I can't seem to figure it out all the same.

CodePudding user response:

This example traverses the data recursively and if key with name "five" is found, yields the value:

import json


def get_key(o, key_name):
    if isinstance(o, dict):
        for k, v in o.items():
            if k == key_name:
                yield v
            else:
                yield from get_key(v, key_name)
    elif isinstance(o, list):
        for v in o:
            yield from get_key(v, key_name)


with open("data.json", "r") as f_in:
    data = json.load(f_in)


print(next(get_key(data, "five")))

Prints:

{'six': 'six'}
  • Related