Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a value within nested json dictionary in python

From the following json, in python, I'd like to extract the value "TEXT". All the keys are constant except for unknown. Unknown could be any string like "a6784t66" or "hobvp*nfe". The value of unknown is not known, only that it will be in that position in each json response.

{
  "A": {
    "B": {
      "unknown": {
        "1": "F",
        "maindata": [
          {
            "Info": "TEXT"
          }
        ]
      }
    }
  }
}

one line json

'{"A":{"B":{"unknown":{"1":"F","maindata":[{"Info":"TEXT"}]}}}}'

How would you get the value of "Text"? (I know how to load the json with json.loads)..but I'm not sure how to get the value of "Text". Thanks.

(I'm not sure what the best title is.)

like image 420
user1959942 Avatar asked Jan 09 '13 02:01

user1959942


1 Answers

You can use a recursive function to dig through every layer and print its value with an indent

def recurse_keys(df, indent = '  '):
    ''' 
    import json, requests, pandas
    r = requests.post(...)  
    rj = r.json() # json decode results query
    j = json.dumps(rj, sort_keys=True,indent=2)            
    df1 = pandas.read_json(j)         
    '''
    for key in df.keys():
        print(indent+str(key))
        if isinstance(df[key], dict):
            recurse_keys(df[key], indent+'   ')
recurse_keys(df1)
like image 143
nagordon Avatar answered Sep 24 '22 06:09

nagordon