使用实例的 __dict__属性,将类对象转为json格式字符串
import json
class Person(object):
def __init__(self):
self.name = 'John'
self.age = 25
self.id = 1
person = Person()
s = json.dumps(person.__dict__)
print(s)
# 输出结果
{"id": 1, "age": 25, "name": "John"}
对于集合的json字符串
json_string = json.dumps([ob.__dict__ for ob in list_obj])
字符串转json
a = "{'name': 'John', 'age': 25, 'id': 1}"
bb = json.loads(a)
print(type(bb))
print(bb)
# 输出结果
<class 'dict'>
{'name': 'John', 'age': 25, 'id': 1}