我有以下问题。我想将复杂对象转换为json字典。我无法直接这样做,因此我最终使用json.dumps()将对象首先生成一个字符串,然后使用json.loads()加载该字符串
我本来希望能够使用json.dump()实现这一点,但这需要我将它放入一个类似文件的对象中,当我想要获取dict数据结构时,它似乎是一个额外的环
有没有一种方法可以在不创建公开写方法的对象的情况下消除对字符串的转换和加载
示例代码:
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)
因此,在明确您的需求之后,您似乎希望将任意的
class
转换为嵌套的dict
,而不是转换为JSON字符串在这种情况下,我建议您使用某种序列化程序/反序列化程序库,如^{} 或^{}
在
pydantic
中实现的示例如下所示:有关高级用法,请查看提供的链接
希望有帮助
相关问题 更多 >
编程相关推荐