Find a value within nested json dictionary in python

前端 未结 3 1217
萌比男神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 09:42

    It is a bit lenghty, but in that example above:

    In [1]: import json
    
    In [2]: s = """\
       ...: {
       ...:   "A": {
       ...:     "B": {
       ...:       "unknown": {
       ...:         "1": "F",
       ...:         "maindata": [
       ...:           {
       ...:             "Info": "TEXT"
       ...:           }
       ...:         ]
       ...:       }
       ...:     }
       ...:   }
       ...: }"""
    
    In [3]: data = json.loads(s)
    
    In [4]: data['A']['B']['unknown']['maindata'][0]['Info']
    Out[4]: u'TEXT'
    

    You basically treat it as a dictionary, passing the keys to get the values of each nested dictionary. The only different part is when you hit maindata, where the resulting value is a list. In order to handle that, we pull the first element [0] and then access the Info key to get the value TEXT.

    In the case of unknown changing, you would replace it with a variable that represents the 'known' name it will take at that point in your code:

    my_variable = 'some_name'
    data['A']['B'][my_variable]['maindata'][0]['Info']
    

    And if I would have actually read your question properly the first time, if you don't know what unknown is at any point, you can do something like this:

    data['A']['B'].values()[0]['maindata'][0]['Info']
    

    Where values() is a variable containing:

    [{u'1': u'F', u'maindata': [{u'Info': u'TEXT'}]}]
    

    A single-item list that can be accessed with [0] and then you can proceed as above. Note that this is dependent on there only being one item present in that dictionary - you would need to adjust a bit if there were more.

提交回复
热议问题