Home > Blockchain >  Get key values for certain fields in JSON response
Get key values for certain fields in JSON response

Time:08-26

My json data would look like this:

{
   "a":1,
   "b":[
      {
         "c":2,
         "d":{
            "e":3
         },
         "f":{
            "g":4
         },
         "h":[
            {
               "i":5
            },
            {
               "j":6
            }
         ]
      }
   ]
}

Is there a way I can get values for certain fields in the response along with their keys. So from this response, the fields for which I expect values are a, c,e,g,i,j along with the respective keys. Eg: [a:1,c:2,e:3,g:4,i:5,j:6]. Could this be done?

CodePudding user response:

You can use a recursive function and store key & value if only value not list or dict.

def get_key_value(dct, res_dct, lst):
    
    for k,v in dct.items():
        if isinstance(v, list):
            for d in v:
                get_key_value(d, res_dct, lst)
        elif isinstance(v, dict):
            get_key_value(v, res_dct, lst)
        else:
            res_dct[k] = v

            # If you want to store in 'list' you can store as string
            lst.append(f'{k}:{v}')
            
            
            

res_dct = {}
lst = []
get_key_value(dct, res_dct, lst)
print(res_dct)
print(lst)

Output:

# res_dct
{'a': 1, 'c': 2, 'e': 3, 'g': 4, 'i': 5, 'j': 6}

# lst
['a:1', 'c:2', 'e:3', 'g:4', 'i:5', 'j:6']

CodePudding user response:

My response contained something like:

{
   "a":1,
   "b":[
      {
         "c":2,
         "d":{
            "e":3
         },
         "f":{
            "g":4,
            "k":[
              "l","m"]
         },
         "h":[
            {
               "i":5
            },
            {
               "j":6
            }
         ]
      }
   ]
}

Which resulted in the error. I have made the following fix for it.

def get_key_value(dct, res_dct, lst):
    for k,v in dct.items():
        if isinstance(v, list):
            for d in v:
                if isinstance(d,dict):
                    get_key_value(d, res_dct, lst)
                else:
                    lst.append(f'{k}:{v}')
        elif isinstance(v, dict):
            get_key_value(v, res_dct, lst)
        else:
            res_dct[k] = v

            # If you want to store in 'list' you can store as string
            lst.append(f'{k}:{v}')
            
res_dct = {}
lst = []
get_key_value(staging_dict, res_dct, lst)
  • Related