如何使用 json 模块将 python 对象转换为 (json) 嵌套字典,而无需创建类似文件的对象?



我有以下问题。我想将复杂对象转换为 json 字典。我无法直接做到这一点,所以我最终使用 json.dumps(( 首先将对象变成一个字符串,然后使用 json.loads(( 加载该字符串。

我希望能够使用 json.dump(( 做到这一点,但这需要我将其放入一个类似文件的对象中,这在想要获取字典数据结构时似乎是一个额外的箍。

有没有办法在不创建公开写入方法的对象的情况下消除对字符串的转换,然后消除加载?

示例代码:

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 字符串。

在这种情况下,我建议您使用某种序列化程序/反序列化程序库,例如pydanticmarshmallow

pydantic中的实现示例如下所示:

import pydantic

class Location(pydantic.BaseModel):
lat: float
lon: float

class WeatherResponse(pydantic.BaseModel):
state: str
temp: float
pressure: float
humidity: str
wind_speed: float
wind_direction: float
clouds: str
location: Location

weather = WeatherResponse(
state="Meteorite shower",
temp=35.5,
pressure=1,
humidity="Wet",
wind_speed=3,
wind_direction=150,
clouds="Cloudy",
location=Location(lat=10, lon=10),
)
weather_dict = weather.dict()
# {'state': 'Meteorite shower', 'temp': 35.5, 'pressure': 1.0, 'humidity': 'Wet', 'wind_speed': 3.0, 'wind_direction': 150.0, 'clouds': 'Cloudy', 'location': {'lat': 10.0, 'lon': 10.0}}

有关高级用法,请查看提供的链接。

希望对您有所帮助!

最新更新