带有列表的对象不可 JSON 序列化

问题描述 投票:0回答:1

请使用此序列化Python 3.11,目标是

{"name": "One", "quantity": 2, "students":[{"first_name": "Geeky", "last_name": "Guy"},{"first_name": "GFG", "last_name": "ocks"}] }
import json
 
class Student():
    def __init__(self):
      pass
 
 
class Team():
    def __init__(self):
        pass
  
student1 = Student()
student1.first_name='Geeky'
student1.last_name='Guy'
student2 = Student()
student2.first_name='GFG'
student2.last_name='ocks'
team = Team()
team.name='One'
team.quantity=2
team.students=[]
team.students.append(student1)
team.students.append(student2)

 
# Serialization
json_data = json.dumps(team.__dict__)
print(json_data)

打印下一个错误

Traceback (most recent call last):
  File "example.py", line 28, in <module>
    json_data = json.dumps(team.__dict__)
  File "/opt/bitnami/python/lib/python3.8/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/opt/bitnami/python/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/opt/bitnami/python/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/opt/bitnami/python/lib/python3.8/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Student is not JSON serializable
python json serialization
1个回答
0
投票

问题是,当您在

json.dumps()
上使用
team.__dict__
时,学生的值只是学生对象 ID,如下所示:
{"name": "One", "quantity": 2, "students": ["<__main__.Student object at 0x000001C2CCAFE810>", "<__main__.Student object at 0x000001C2CCAFE6F0>"]}
并且该对象不可 JSON 序列化,这就是您收到错误的原因。

解决这个问题的方法,因为你的数据很简单。您可以使用参数

json.dumps()
 来调用 
default=vars

如果指定,默认值应该是一个为无法序列化的对象调用的函数。它应该返回对象的 JSON 可编码版本或引发 TypeError。如果未指定,则会引发 TypeError。

vars()
是内置函数。

返回模块、类、实例或任何其他具有 __dict__ 属性的对象的 __dict__ 属性。

因此,您所要做的就是将 json 转储更改为:

json_data = json.dumps(team, default=vars)
print(json_data)

# {"name": "One", "quantity": 2, "students": [{"first_name": "Geeky", "last_name": "Guy"}, {"first_name": "GFG", "last_name": "ocks"}]}
© www.soinside.com 2019 - 2024. All rights reserved.