python实现class对象转换成json/字典的方法

WBOY
Release: 2016-06-10 15:05:53
Original
2772 people have browsed it

本文实例讲述了python实现class对象转换成json字典的方法。分享给大家供大家参考,具体如下:

# -*- encoding: UTF-8 -*-
class Student:
  name = ''
  age = 0
  def __init__(self, name, age):
    self.name = name
    self.age = age
def convert_to_dict(obj):
  '''把Object对象转换成Dict对象'''
  dict = {}
  dict.update(obj.__dict__)
  return dict
def convert_to_dicts(objs):
  '''把对象列表转换为字典列表'''
  obj_arr = []
  for o in objs:
    #把Object对象转换成Dict对象
    dict = {}
    dict.update(o.__dict__)
    obj_arr.append(dict)
  return obj_arr
def class_to_dict(obj):
  '''把对象(支持单个对象、list、set)转换成字典'''
  is_list = obj.__class__ == [].__class__
  is_set = obj.__class__ == set().__class__
  if is_list or is_set:
    obj_arr = []
    for o in obj:
      #把Object对象转换成Dict对象
      dict = {}
      dict.update(o.__dict__)
      obj_arr.append(dict)
    return obj_arr
  else:
    dict = {}
    dict.update(obj.__dict__)
    return dict
stu = Student('zhangsan', 20)
print '-----------'
print convert_to_dict(stu)
print '-----------'
print convert_to_dicts([stu, stu])
print '-----------'
print class_to_dict(stu)
print '-----------'
print class_to_dict([stu, stu])
stua = Student('zhangsan', 20)
stub = Student('lisi', 10)
stu_set = set()
stu_set.add(stua)
stu_set.add(stub)
print class_to_dict(stu_set)

Copy after login

运行结果如下:

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

Copy after login

希望本文所述对大家Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!