以新格式重新组合JSON文件

时间:2015-12-07 23:05:55

标签: python json

我需要帮助重新排序这个JSON数据:

此刻我有这个文件:

[{"aName":{"name":"somename","vendor":"vendor1"}},
 {"bName":{"name":"somename","vendor":"vendor2"}},
 {"cName":{"name":"othername","vendor":"vendor1"}
}]

我需要像这样重新订购:

[{"name":"vendor1"},
 {"child":[{"name":"somename","id":"aName"},
           {"name":"othername","id":"cName"}]},
 {"name":"vendor2"},
 {"child":[{"name":"somename","id":"bName"}]}]

我正在尝试这个:

new format = []

for i in old_format:
    new_format.setdefault(i['vendor'], []).append({"children":{"name":i['name'],"id":i}})

它“更接近”,但不是我想要的

{
       "vendor1":[
          {
             "children":{
                "name":"somename",        
                "id":"aName"
             }
          },
          {
             "children":{
                "name":"othername",
                "id":"cName"
             }
          }
       ],
       "vendor2":[
          {
             "children":{
                "name":"somename",
                "id":"bName"
             }
          }
       ]
    }

我会感激任何建议。

1 个答案:

答案 0 :(得分:1)

您正在使用的数据表示有点奇怪...您有很多带有一个条目的词典,这表明您最好不要重新考虑如何存储数据。< / p>

那就是说,这段代码应该做你想做的事情:

vendors = {}
for entry in data:
    for identifier, info in entry.items():
        children = vendors.setdefault(info['vendor'], [])
        children.append({
            'name': info['name'],
            'id': identifier
            })

res = []
for vendor, children in vendors.items():
    res.append({'name': vendor})
    res.append({'child': children})

此处data是您的输入 - 字典列表 - 结果为res

[{'name': 'vendor2'},
 {'child': [{'id': 'bName', 'name': 'somename'}]},
 {'name': 'vendor1'},
 {'child': [{'id': 'aName', 'name': 'somename'},
   {'id': 'cName', 'name': 'othername'}]}]