python中用户定义类的JSON转储

2024-06-30 15:27:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望我的数据是这样的:(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


Tags: keyselfforinitdeflistclassmisc
1条回答
网友
1楼 · 发布于 2024-06-30 15:27:14

在转储到json之前,需要显式地将数据转换为可序列化的类型,如dict或{}。您可以使用列表理解来完成此操作:

>>> 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"}]'

相关问题 更多 >