This article mainly introduces how to convert a class object into a json dictionary using python, and analyzes the related skills of Python type conversion using examples, for more information about how to convert a class object to a json dictionary in python, see the following example. We will share this with you for your reference. The details are as follows:
#-*-Encoding: UTF-8-*-class Student: name = ''age = 0 def _ init _ (self, name, age): self. name = name self. age = agedef convert_to_dict (obj): ''' converts an Object to a Dict Object ''' dict = {} dict. update (obj. _ dict _) return dictdef convert_to_dicts (objs): ''' converts the object list to the dictionary list ''' obj_arr = [] for o in objs: # convert an Object to a Dict Object dict ={} dict. update (o. _ dict _) obj_arr.append (dict) return obj_arrdef class_to_dict (obj): ''' sets an object (single object, list, and set are supported) convert to the dictionary ''' is_list = obj. _ class _ = []. _ class _ is_set = obj. _ class _ = set (). _ class _ if is_list or is_set: obj_arr = [] for o in obj: # convert an Object to a Dict Object dict ={} dict. update (o. _ dict _) obj_arr.append (dict) return obj_arr else: dict ={} dict. update (obj. _ dict _) return dictstu = Student ('hangsan ', 20) print' ----------- 'print convert_to_dict (stu) print '----------- 'converprint t_to_dicts ([stu, stu]) print '----------- 'print class_to_dict (stu) print' ----------- 'print class_to_dict ([stu, stu]) stua = Student ('hangsan', 20) stub = Student ('lisi ', 10) stu_set = set () stu_set.add (stua) stu_set.add (stub) print class_to_dict (stu_set)
The running result is as follows:
-----------{'age': 20, 'name': 'zhangsan'}-----------[{'age': 20, 'name': 'zhangsan'}, {'age': 20, 'name': 'zhangsan'}]-----------{'age': 20, 'name': 'zhangsan'}-----------[{'age': 20, 'name': 'zhangsan'}, {'age': 20, 'name': 'zhangsan'}][{'age': 10, 'name': 'lisi'}, {'age': 20, 'name': 'zhangsan'}]
I hope this article will help you with Python programming.