Find a value within nested json dictionary in python

前端 未结 3 1219
萌比男神i
萌比男神i 2020-12-28 09:04

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 \

3条回答
  •  梦谈多话
    2020-12-28 10:05

    As you said that unknown was at a fixed place You can do the following

    import json
    s=json.loads('{"A":{"B":{"unknown":{"1":"F","maindata":[{"Info":"TEXT"}]}}}}')
    i=s["A"]["B"].keys()
    x=i[0]   # Will store 'unknown' in x, whatever unknown is
    print s['A']['B'][x]['maindata'][0]['Info']    #here x dictionary index is used after B as its value will be the value for unknown
    

    This should do the job, since only the unknown key is really 'unknown'

提交回复
热议问题