Home > Back-end >  Getting the parent of a element in a .json file
Getting the parent of a element in a .json file

Time:01-11

I have a .json file with a lot of elements. I would like to be able to search for a element value and check it's parent/what the element is inside of. Here I have a sample of my .json file.

{
  "users": {
    "123467890": {
      "lvl": 100,
      "xp": 1000,
      "lastMessage": 91.996059
    }
  }
}

So lets say I chose lvl as my element. How would I get it's parent's value without hardcoding it?

CodePudding user response:

Iterate through the dictionary and add the keys that contain a value["lvl"] of 100.

d = {
  "users": {
    "123467890": {
      "lvl": 100,
      "xp": 1000,
      "lastMessage": 91.996059
    },
    "test": {
      "lvl": 1,
      "xp": 0,
      "lastMessage": 91.996059
    },
  }
}

lvl_100_users = []
for user_id, properties in d["users"].items():
    print(f"User ID: {user_id}; Properties: {properties}")
    if properties["lvl"] == 100:
        lvl_100_users.append(user_id)

print(lvl_100_users)

Outputs:

User ID: 123467890; Properties: {'lvl': 100, 'xp': 1000, 'lastMessage': 91.996059}
User ID: test; Properties: {'lvl': 1, 'xp': 0, 'lastMessage': 91.996059}
['123467890']

CodePudding user response:

Here, obj refers to your json object and key refers to the "lvl" (your element).

 def json_extract(obj, key):
    """Recursively fetch values from nested JSON."""
    arr = []
    def extract(obj, arr, key, parent=None):
        """Recursively search for values of key in JSON tree."""
        if isinstance(obj, dict):
            if key in obj.keys():
                arr.append(parent)
                return parent
            for k, v in obj.items():
                if isinstance(v, (dict, list)):
                    extract(v, arr, key, k)
        elif isinstance(obj, list):
            for item in obj:
                extract(item, arr, key, parent)
        return arr
    values = extract(obj, arr, key)
    return values
  •  Tags:  
  • Related