Home > Software design >  Is there any way to find a specific data in json, without specifying the category
Is there any way to find a specific data in json, without specifying the category

Time:09-29

I'm trying to make a script that grabs the "name" field, without me specifying the id

{
  "accounts" : {
    "random id" : {
      "name" : "random name" 
    }
  }
}

If I wanna take the "name", I have to do something like

a = json.loads(jsondata)

b = a["accounts"]

c = b["random id"]

print(str(c["name"]))

But I don't know the id, how can I make it get the "name" without opening "accounts"....?

CodePudding user response:

The object a that is returned by json.loads is a nested dictionary. You can look through the keys of the dictionary and check if there is a key that matched your searchstring (e.g. "name"). If there is, return the value. If there is no key that matches, you check every value in the dict and check if the value itself is a dict (so this would be the second level dict). If it is, you recursively call the function again.

def find_recursive(dictionary, key):
    if key in dictionary:
        return dictionary[key]
    for value in dictionary.values():
        if isinstance(value, dict):
            return find_recursive(value, key)
>>> find_recursive(a, 'name')
'random name'

CodePudding user response:

This should work:

import json
   
json = json.loads('{"accounts" : {"random id" : {"name" : "random name" }}}')
accounts = json["accounts"]
    
for value in json["accounts"].values():
    print(value["name"])
  • Related