here how want data : (key=name, value=[dob,[misc1, misc2,..]])
# 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={} in inputnames: m = myemp(i[0],i[1]) emps[m] = m print(emps) # prints addresses of variables # actual data use following lines ea in emps: emps[ea].printme() try: open('data.json','w') wfd: json.dump(emps, wfd) except ioerror ioerr: print('file error: ',str(ioerr)) wfd.close()
the above gives me error: typeerror: key <main.myemp object @ 0x10143d588> not string unable figure out how dump dict of myemp data structures json
before can dump json
need explicitly convert data serializable type dict
or list
. using list comprehension:
>>> d = [{'key':ea.nm, 'value':[ea.details.dob, ea.details]} 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"}]'
Comments
Post a Comment