(转)Python 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