use_json.py 673 B

1234567891011121314151617181920212223242526
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import json
  4. d = dict(name='Bob', age=20, score=88)
  5. data = json.dumps(d)
  6. print('JSON Data is a str:', data)
  7. reborn = json.loads(data)
  8. print(reborn)
  9. class Student(object):
  10. def __init__(self, name, age, score):
  11. self.name = name
  12. self.age = age
  13. self.score = score
  14. def __str__(self):
  15. return 'Student object (%s, %s, %s)' % (self.name, self.age, self.score)
  16. s = Student('Bob', 20, 88)
  17. std_data = json.dumps(s, default=lambda obj: obj.__dict__)
  18. print('Dump Student:', std_data)
  19. rebuild = json.loads(std_data, object_hook=lambda d: Student(d['name'], d['age'], d['score']))
  20. print(rebuild)