python 类对象转json字符串

使用实例的 __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}

 


版权声明:本文为enter89原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。