Q:

Convert the following JSON into Vehicle Object using python programming

belongs to collection: Python OOP Exercises

0

Convert the following JSON into Vehicle Object

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

For example, we should be able to access Vehicle Object using the dot operator like this.

vehicleObj.name, vehicleObj.engine, vehicleObj.price

All Answers

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

Solution:

import json

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

def vehicleDecoder(obj):
        return Vehicle(obj['name'], obj['engine'], obj['price'])

vehicleObj = json.loads('{ "name": "Toyota Rav4", "engine": "2.5L", "price": 32000 }',
           object_hook=vehicleDecoder)

print("Type of decoded object from JSON Data")
print(type(vehicleObj))
print("Vehicle Details")
print(vehicleObj.name, vehicleObj.engine, vehicleObj.price)

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

total answers (1)

Check whether following json is valid or invalid. ... >>
<< Convert the following Vehicle Object into JSON usi...