【发布时间】:2021-12-29 00:04:37
【问题描述】:
我有两种方法可以用json.dumps()表示Python对象
第一:
person = {
"name": "John",
"age": 30,
"city": "New York"
}
第二:
class Person:
def _init_(self, name, age, city):
self.name = name
self.age = age
self.city = city
person = Person("John", 30, "New York")
然后我尝试p1 = json.dumps(person),第二种方式是it's not JSON serializable。
所以基本上对于 Python,json.dumps 只适用于像 dict 对象这样的内置对象?
【问题讨论】:
-
是的;默认情况下,
json模块只知道如何序列化内置类型。查看json.JSONEncoder了解如何序列化您自己的类的实例。
标签: python json serialization