Search code examples
pythonjsonserialization

Object with list is not JSON serializable


PLease with this serialization Python 3.11, the target is

{"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)

print the next error

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

Solution

  • The problem is that when you use json.dumps() on your team.__dict__ the value of students is just the students object id like so: {"name": "One", "quantity": 2, "students": ["<__main__.Student object at 0x000001C2CCAFE810>", "<__main__.Student object at 0x000001C2CCAFE6F0>"]} and that object is not JSON serializable which is why you are getting an error.

    A way to solve this, because your data is simple. You can call json.dumps() with the parameter default=vars

    If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.

    and vars() is a builtin function.

    Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

    So all you have to do is change your json dumps to this:

    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"}]}