将嵌套结构转换为字符串

时间:2019-08-21 19:43:25

标签: python json string python-2.7 list

我的数据由多个嵌套的字典和列表组成,我试图将列表转换为字典,而该字典的一个元素中没有嵌套结构。

data = [
    [
        u'abc', u'1.2.3.4', 52, 
        [u'prod', u'linux'], 
        u'jack',
        [u'2019-08-15', u'2019-06-10'],  
        {u'dc': u'NA', u'network': u'public'}
    ], 
    [
        u'xyz', u'127.0.0.1', 126, 
        [u'prod', u'linux', u'backup'], 
        u'rich', 
        [u'2019-03-21', u'2019-05-01'], 
        {u'network': u'public', u'owner': u'security team'}
    ],
    [
        u'pqr', u'5.6.7.8', 125,  
        [u'stage', u'ubuntu'],
         u'kevin', 
         [], 
        {u'newtwork': u'private', u'type': u'sql', u'owner': u'security team'}
    ]
]

key_list = ['hostname', 'ip_address', 'num_process', 'usage', 'user', 'restarts', 'tags']

我尝试使用zip(),但由于key_list tags中的最后一个元素一直困扰着我,因此我能够接近想要达到的目标。 我碰到了这个页面 Convert the nested json into a dictionary format with no nested objects

这给了我希望,但是后来我在此解决方案中发现数据仅具有一个嵌套列表,因此该方法很好,但是我的数据具有多个嵌套列表,并且将来还会增加。

如何完善代码,以便将来在数据中添加新列表时,解决方案也不会受到影响。

[
    {
        "hostname":"abc",
        "ip_address":"1.2.3.4",
        "num_process":"52",
        "usage":"prod, linux",
        "owner":"jack",
        "restarts":"2019-08-15, 2019-06-10",
        "dc":"NA",
        "network":"public"
    },
    {
    "hostname":"xyz",
    "ip_address":"127.0.0.1",
    "num_process":"126",
    "usage":"prod, linux,backup",
    "user":"rich",
    "restarts":"2019-03-21, 2019-05-01",
    "owner":"security team",
    "network":"public"
    },
    {
        "hostname":"pqr",
        "ip_address":"5.6.7.8",
        "num_process":"125",
        "usage":"stage, ubuntu",
        "owner":"kevin",
        "restarts":"",
        "user":"security team",
        "newtwork":"private",
        "type":"sql"
    }
]

1 个答案:

答案 0 :(得分:0)

尝试一下:

def get_mapping(data, keys):
    for entry in data:
        result = dict(zip(key_list, (value for value in entry if not isinstance(value, dict))))
        for value in entry:
            if isinstance(value, dict):
                result.update(value)
        yield result

list(get_mapping(data, key_list))

输出:

[{'hostname': 'abc',
  'ip_address': '1.2.3.4',
  'num_process': 52,
  'usage': ['prod', 'linux'],
  'user': 'jack',
  'restarts': ['2019-08-15', '2019-06-10'],
  'dc': 'NA',
  'network': 'public'},
 {'hostname': 'xyz',
  'ip_address': '127.0.0.1',
  'num_process': 126,
  'usage': ['prod', 'linux', 'backup'],
  'user': 'rich',
  'restarts': ['2019-03-21', '2019-05-01'],
  'network': 'public',
  'owner': 'security team'},
 {'hostname': 'pqr',
  'ip_address': '5.6.7.8',
  'num_process': 125,
  'usage': ['stage', 'ubuntu'],
  'user': 'kevin',
  'restarts': [],
  'newtwork': 'private',
  'type': 'sql',
  'owner': 'security team'}]
相关问题