Search code examples
pythonjsonnsjsonserializationjsonserializer

serializing a json file from list of list


So i have a list of elements:

elements = [room1, room2, room3]

I also have a list of key/value attributes that each room has:

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

is there a way to serialize this two lists into a json file structured like this:

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

I am on this weird platform that doesnt support dictionaries so I created a class for them:

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

then i found a peiece of code that would allow me to create a basic json code from two parallel lists:

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

but this code desnt give me the {room1: [{ ... structure

Any ideas would be great. This software I am working with is based on IronPython2.7

Ok, so the above worked great. I got a great feedback from Comments. I have one more variation that I didnt account for. Sometimes when I try to mix more than singe element type (rooms, columns etc) they might not have the same amount of attributes. For example a room can have (level, finish and finish) while column might have only thickness and material. If i kept it all organized in parallel lists key/value is it possible to modify the definition below:

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

How would i need to modify the definition below to make it work? Again I want to export a json file.


Solution

  • I don't know how Python can even work without dictionaries, so please just test this and tell me the error it shows you:

    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)