用户定义的类在python中的JSON转储

时间:2016-09-02 00:22:57

标签: python json dictionary dump user-defined-types

以下是我想要的数据:( key = name,value = [dob,[misc1,misc2,..]])

    # my sample code
inputNames = [
('james', ['1990-01-19', ['james1', 'james2', 'james3'] ]),
('julie', ['1991-08-07', ['julie1', 'julie2'] ]),
('mikey', ['1989-01-23', ['mikey1'] ]),
('sarah', ['1988-02-05', ['sarah1', 'sarah2', 'sarah3', 'sarah4'] ])
]
class empData (list):
    def __init__ (self, misc=None):
            list.__init__([])
            # print('add empdata: ',misc[0],misc[1])
            self.dob = misc[0]
            self.extend(misc[1])
    def edprint(self):
            return(self.dob, self)
class myEmp():
    def __init__ (self, anm, amisc=None):
            self.nm = anm
            self.details = empData(amisc)
    def printme(self):
            print(self.nm, self.details.edprint())

emps={}
for i in inputNames:
    m = myEmp(i[0],i[1])
    emps[m] = m
print(emps) 
# prints addresses of variables

# for actual data use the following lines
for ea in emps:    
    emps[ea].printme() 

try:    
   with open('data.json','w') as wfd:
             json.dump(emps, wfd)              
except IOError as ioerr:
            print('File error: ',str(ioerr))
wfd.close()

上面给出了一个错误:TypeError:key< main .myEmp对象位于0x10143d588>不是一个字符串 我无法弄清楚如何将myEmp数据结构的dict转储为JSON

1 个答案:

答案 0 :(得分:0)

在转储到json之前,您需要明确地将数据转换为可序列化的类型,例如dictlist。你可以使用列表理解来做到这一点:

>>> d = [{'key':ea.nm, 'value':[ea.details.dob, ea.details]} for ea in emps]
>>> json.dumps(d)
'[{"value": ["1991-08-07", ["julie1", "julie2"]], "key": "julie"}, {"value": ["1989-01-23", ["mikey1"]], "key": "mikey"}, {"value": ["1990-01-19", ["james1", "james2", "james3"]], "key": "james"}, {"value": ["1988-02-05", ["sarah1", "sarah2", "sarah3", "sarah4"]], "key": "sarah"}]'