Q:

Convert the following Vehicle Object into JSON using python programming

belongs to collection: Python OOP Exercises

0

Convert the following Vehicle Object into JSON

import json

class Vehicle:
    def __init__(self, name, engine, price):
        self.name = name
        self.engine = engine
        self.price = price

vehicle = Vehicle("Toyota Rav4", "2.5L", 32000)

# Convert it into JSON format

Expected Output:

{
    "name": "Toyota Rav4",
    "engine": "2.5L",
    "price": 32000
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Solution:

import json
from json import JSONEncoder

class Vehicle:
    def __init__(self, name, engine, price):
        self.name = name
        self.engine = engine
        self.price = price

class VehicleEncoder(JSONEncoder):
        def default(self, o):
            return o.__dict__

vehicle = Vehicle("Toyota Rav4", "2.5L", 32000)

print("Encode Vehicle Object into JSON")
vehicleJson = json.dumps(vehicle, indent=4, cls=VehicleEncoder)
print(vehicleJson)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Convert the following JSON into Vehicle Object usi... >>
<< Access the nested key ‘salary’ from the follow...