; ;

python 将长串内容转换成json串

第一种方式转换

#encoding=utf-8
import json
class Employee(object):
  def __init__(self, name, age, sex, tel): 
    self.name = name
    self.age = age
    self.sex = sex
    self.tel = tel

  # 将序列化函数定义到类里面
  def obj_json(self, obj_instance):
    return {
      'name': obj_instance.name,
      'age': obj_instance.age,
      'sex': obj_instance.sex,
      'tel': obj_instance.tel }

emp = Employee('Lily', 24, 'female', '18223423423')
print(json.dumps(emp, default = emp.obj_json))

  

 

 

第二种方式 转换

import json
class Employee(object):
  def __init__(self, name, age, sex, tel):
    self.name = name
    self.age = age
    self.sex = sex
    self.tel = tel
emp = Employee('zhangjun', 24, 'female', 'XXXXXXX')
print(emp.__dict__)  #返回所有的内置方法
print(json.dumps(emp, default = \
lambda Employee: Employee.__dict__))


print(json.dumps(emp, default = lambda emp: emp.__dict__))

  

 

posted @ 2020-01-05 14:39  做梦的人-  阅读(701)  评论(0编辑  收藏  举报