简体   繁体   中英

Modifying Json Data using Python

Below is my data.

input = {'key1': {'key1.1': 'value1.1',
                  'key1.2': 'value1.2',
                  'key1.3': {'key1.3.1': 'value1.3.1', 'key1.3.2': [{'key1.3.2.1': 'value1.3.2.1'},
                                                                    {'key1.3.2.2': 'value1.3.2.2'}
                                                                    ]
                             }
                  },
         'key2': 'value2'}

I want to recursively convert inner inner key/values into a list of sub dictionaries with Name and Value as their keys. Below is my desired output.

output = {"key1": [{"NAME": "key1.1", "VALUE": "value1.1"},
                   {"NAME": "key1.2", "VALUE": "value1.2"},
                   {"NAME": "key1.3", "VALUE": [{"NAME": "key1.3.1", "VALUE": "value1.3.1"},
                                                {"NAME": "key1.3.2", "VALUE": [{"NAME": "key1.3.2.1", "VALUE": "value1.3.2.1"},
                                                                               {"NAME": "key1.3.2.2", "VALUE": "value1.3.2.2"}]
                                                 }]
                    }],
          "key2": "value2"}

Below is what is tried but it is not working correctly for list of dictionaries (ex: "key1.3.2.1": "value1.3.2.1"). Is there a way to achieve this output?

def my_func(d):
    new_dict = {}
    for k, v in d.items():
        a = []
        if isinstance(v, dict):
            for key, value in my_func(v).items():
                x = {}
                y = {}
                x['NAME'] = key
                y['VALUE'] = value
                z = {**x, **y}
                a.append(z)
        elif isinstance(v, list):
            a = [my_func(item) if isinstance(item, dict) else item for item in v]
        else:
            a = v
        new_dict[k] = a
    return new_dict


output = json.dumps(my_func(input), indent=2)
print(output)

You can use recursive function

def fun(d, res=None):
    if res is None:
        res = []
    for k, v in d.items():
        if isinstance(v, dict):
            res.append({'NAME': k, 'VALUE': fun(v)})
        elif isinstance(v, list):
            temp = {'NAME': k, 'VALUE': []}
            for x in v:
                temp['VALUE'].append(fun(x)[0])
            res.append(temp)
        else:
            res.append({'NAME': k, 'VALUE': v})
    return res

d = {k: fun(v) if isinstance(v, dict) else v  for k, v in d.items()}
print(d)

Output:

{'key1': [{'NAME': 'key1.1', 'VALUE': 'value1.1'},
          {'NAME': 'key1.2', 'VALUE': 'value1.2'},
          {'NAME': 'key1.3',
           'VALUE': [{'NAME': 'key1.3.1', 'VALUE': 'value1.3.1'},
                     {'NAME': 'key1.3.2',
                      'VALUE': [{'NAME': 'key1.3.2.1', 'VALUE': 'value1.3.2.1'},
                                {'NAME': 'key1.3.2.2',
                                 'VALUE': 'value1.3.2.2'}]}]}],
 'key2': 'value2'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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