从列表的列表中序列化一个 json 文件

serializing a json file from list of list

所以我有一个元素列表:

elements = [room1, room2, room3]

我还有每个房间具有的 key/value 属性列表:

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:

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: [{ ... 结构

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

好的,以上方法效果很好。我从评论中得到了很好的反馈。我还有一种我没有考虑到的变化。有时,当我尝试混合多个元素类型(房间、柱子等)时,它们可能没有相同数量的属性。例如,一个房间可以有 (level, finish 和 finish),而柱子可能只有厚度和 material。如果我把它全部组织在平行列表中 key/value 是否可以修改下面的定义:

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

我需要如何修改下面的定义才能使其生效?我想再次导出一个 json 文件。

我不知道 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)

这可能有效。

#-*- 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))