从列表列表中序列化json文件

时间:2015-01-31 17:14:00

标签: python json nsjsonserialization jsonserializer

所以我有一个元素列表:

elements = [room1, room2, room3]

我还有一个每个房间都有的键/值属性列表:

keys = ["level", "finish1", "finish2"]
values = [["ground", "paint1", "carpet1"],["ground", "paint1", "paint2"], ["second level", "paint1", "paint2"]]

有没有办法将这两个列表序列化为一个结构如下的json文件:

{'room1': [{'level': 'ground', 'finish1': 'paint1', 'finish2': 'carpet1'}],'room2': [{'level': 'ground', 'finish1': 'paint1', 'finish2': 'paint2'}],'room3': [{'level': 'second level', 'finish1': 'paint1', 'finish2': 'paint2'}]}

我在这个不支持词典的奇怪平台上,所以我为他们创建了一个类:

class collection():
def __init__(self,name,key,value):
    self.name = name
    self.dict = {}
    self.dict[key] = value
def __str__(self):
    x = str(self.name) + " collection"
    for key,value in self.dict.iteritems():
        x = x + '\n'+ '  %s= %s ' % (key, value)
    return x

然后我找到了一段代码,允许我从两个并行列表中创建一个基本的json代码:

def json_list(keys,values):
lst = []
for pn, dn in zip(values, keys):
    d = {}
    d[dn]=pn
    lst.append(d)
return json.dumps(lst)

但是这段代码给了我{room1:[{... structure

任何想法都会很棒。我正在使用的这个软件基于IronPython2.7

好的,所以上面的效果很好。我从评论中得到了很好的反馈。我还有一个我没有考虑的变体。有时当我尝试混合多种单元类型(房间,列等)时,它们可能没有相同数量的属性。例如,房间可以有(水平,完成和完成),而列可能只有厚度和材料。如果我保持所有组织并行列表键/值是可以修改下面的定义:

keys = [[thickness, material],[level,finish,finish]]
values = [[100,paint],[ground,paint,paint]]
elements = [column,room]

我如何修改下面的定义以使其有效?我想再次导出一个json文件。

2 个答案:

答案 0 :(得分:1)

我不知道Python如何在没有字典的情况下工作,所以请测试一下并告诉我它向您显示的错误:

import json

elements = ['r1','r2','r3']
keys = ["level", "finish1", "finish2"]
values = [["ground", "paint1", "carpet1"],["ground", "paint1", "paint2"], ["second level", "paint1", "paint2"]]
d = dict()

for (index, room) in enumerate(elements):
    d[room] = dict()
    for (index2, key) in enumerate(keys):
        d[room][key] = values[index][index2]

print json.dumps(d)

答案 1 :(得分:1)

这可能有效。

#-*- encoding: utf-8 -*-
import json

elements = ["room1", "room2", "room3"]
keys = ["level", "finish1", "finish2"]
values = [["ground", "paint1", "carpet1"],["ground", "paint1", "paint2"], ["second level", "paint1", "paint2"]]

what_i_want = dict((room, [dict(zip(keys, value))])
                   for room, value in zip(elements, values))
print(json.dumps(what_i_want))