简体   繁体   中英

Python Nested Obj to JSON

How can I get JSON from nested python object

class simplobj:

 def _init_(self,fname,lname,depart):
       self.fname=fname
       self.lname=lname
       self.depart = depart

class jsonobj:

  array = [] 
  def _init_(self,time,listOfSimpleObj):
       self.time = time
       self.array = listofSimpleObj 

class Main:

  listOfSimpleObj =[]
  sobj = simplobj("fname1","lname1","depart1")
  listOfSimpleObj.append(sobj)
  outputjsonobj = jsonobj(time,listOfSimpleObj)
  output = json.dumps(outputjsonobj._dict_)



output: { "time" : "time", "array":  [ 
{ "fname": "fname1", "lname": "lname1", "depart": "depart1"},
{ "fname": "fname2", "lname": "lname2", "depart": "depart2"},
{ "fname": "fname3", "lname": "lname3", "depart": "depart3"}  ] }

You could create a json.JSONEncoder to specify how your classes should be serialized:

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, simplobj) or isinstance(obj, jsonobj):
            return obj.__dict__
        return json.JSONEncoder.default(self, obj)

...

output = json.dumps(outputjsonobj, cls=MyEncoder)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM