(转)Python JSON序列化

本文详细介绍了如何使用Python的json模块将字典、列表、对象等数据结构转换为JSON格式,并通过反序列化将其从JSON字符串转换回原始数据类型。涵盖了从基本数据类型到复杂对象的数据转换过程。
  1. import json  
  2.   
  3. # dict to json  
  4. d=dict(name="cui",age=20,score=88)  
  5. print json.dumps(d)  
  6.   
  7. #list to json  
  8. l=["cui",20,88]  
  9. print json.dumps(l)  
  10.   
  11. #object to json  
  12. class Student(object):  
  13.     """docstring for Student"""  
  14.     def __init__(self):  
  15.         super(Student, self).__init__()  
  16.         self.age=20  
  17.         self.name="cui"  
  18.         self.score=88  
  19.   
  20. print json.dumps(Student(),default=lambda obj:obj.__dict__)  
  21.   
  22. #json to dict  
  23. json_str='{"age": 20, "score": 88, "name": "cui"}'    
  24. d= json.loads(json_str)  
  25. print d  
  26.   
  27. #json to list  
  28. json_str='["cui", 20, 88]'  
  29. l=json.loads(json_str)  
  30. print l  
  31.   
  32. #json to object  
  33. json_str='{"age": 20, "score": 88, "name": "cui"}'  
  34. def dict2Student(d):  
  35.     s=Student()  
  36.     s.name=d["name"]  
  37.     s.age=d["age"]  
  38.     s.score=d["score"]  
  39.     return s  
  40.   
  41. student=json.loads(json_str,object_hook=dict2Student)  

转载于:https://www.cnblogs.com/liguangxu/p/5506990.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值