在Python中将类对象转换为 JSON
类对象到 JSON 的转换是使用Python中的 json 包完成的。 json.dumps() 将Python对象转换为 json字符串。每个Python对象都有一个由 __dict__ 表示的属性,它存储对象的属性。
- 对象首先使用 __dict__ 属性转换为字典格式。
- 这个新创建的字典作为参数传递给 json.dumps() ,然后产生一个 JSON 字符串。
Syntax: json.dumps(Object obj)
Parameter: Expects a dictionary object.
Return: json string
以下Python代码将Python类 Student 对象转换为 JSON。
Python3
# import required packages
import json
# custom class
class Student:
def __init__(self, roll_no, name, batch):
self.roll_no = roll_no
self.name = name
self.batch = batch
class Car:
def __init__(self, brand, name, batch):
self.brand = brand
self.name = name
self.batch = batch
# main function
if __name__ == "__main__":
# create two new student objects
s1 = Student("85", "Swapnil", "IMT")
s2 = Student("124", "Akash", "IMT")
# create two new car objects
c1 = Car("Honda", "city", "2005")
c2 = Car("Honda", "Amaze", "2011")
# convert to JSON format
jsonstr1 = json.dumps(s1.__dict__)
jsonstr2 = json.dumps(s2.__dict__)
jsonstr3 = json.dumps(c1.__dict__)
jsonstr4 = json.dumps(c2.__dict__)
# print created JSON objects
print(jsonstr1)
print(jsonstr2)
print(jsonstr3)
print(jsonstr4)
输出:
{"roll_no": "85", "name": "Swapnil", "batch": "IMT"}
{"roll_no": "124", "name": "Akash", "batch": "IMT"}
{"brand": "Honda", "name": "city", "batch": "2005"}
{"brand": "Honda", "name": "Amaze", "batch": "2011"}