0

How can I serialize an object that contains a list of objects to JSON

The error I get :

TypeError: Object of type person is not JSON serializable

import json

class person:
    def __init__(self, name, cars):
        self._name = name
        self._cars = cars
    
class car:
    def __init__(self, brand, color):
        self._brand = brand
        self._color = color

Jason = person("Jason", [car("Toyota", "Blue"), car("Honda", "Red")])

json = json.dumps(Jason)
print(json)

The output I want :

    {
        "name": "Jason",
        "cars":[
            {
                "brand": "Toyota",
                "color": "Blue"
            },
            {
                "brand": "Honda",
                "color": "Red"
            }
        ]
    }
  • Why should a single person be turned into a JSON list? BTW: For a better question, include the output you want (not a sketch thereof!) and (in case) the output you got. Also, include a [mcve]! – Ulrich Eckhardt Jun 03 '22 at 17:56
  • This should answer your question https://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable – jprebys Jun 03 '22 at 17:56

0 Answers0