简体   繁体   English

获取 JSON 响应中某些字段的键值

[英]Get key values for certain fields in JSON response

My json data would look like this:我的 json 数据如下所示:

{
   "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.因此,从这个响应中,我期望值的字段是 a, c,e,g,i,j 以及相应的键。 Eg: [a:1,c:2,e:3,g:4,i:5,j:6].例如:[a:1,c:2,e:3,g:4,i:5,j:6]。 Could this be done?这可以做到吗?

You can use a recursive function and store key & value if only value not list or dict.如果只有值不是列表或字典,您可以使用递归 function 并存储key & value

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: 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']

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM