I have the following issue. I want to convert a complex object to a json dictionary. I am unable to do it directly so I end up using json.dumps() to make the object into a string first and then load that string with json.loads().
I was expecting to be able to do it with json.dump(), however that requires that I put it into a file-like object which seems like an extra hoop to go through when wanting to get a dict data structure.
Is there a way to eliminate the conversion to string and then the load without creating an object that exposes a write method?
Sample code:
import json
class Location():
def __init__(self, lat, lon):
self.lat = lat
self.lon = lon
class WeatherResponse():
def __init__(self,
state: str,
temp: float,
pressure: float,
humidity: float,
wind_speed: float,
wind_direction: float,
clouds: str,
location: Location):
self.state = state
self.temp = temp
self.pressure = pressure
self.humidity = humidity
self.wind_speed = wind_speed
self.wind_direction = wind_direction
self.clouds = clouds
self.location = location
weather = WeatherResponse(state = "Meteorite shower",
temp = 35.5,
pressure = 1,
humidity = "Wet",
wind_speed = 3,
wind_direction = 150,
clouds = "Cloudy",
location = Location(10, 10))
weather_json = json.dump(weather) #Needs a file like object
weather_string = json.dumps(weather, default = lambda o: o.__dict__)
weather_dict = json.loads(weather_string)
print(weather_dict)