繁体   English   中英

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

[英]How do I convert a python object to (json) nested dict using the json module, without making a file-like object?

我有以下问题。 我想将复杂对象转换为 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 字符串。

在这种情况下,我建议您使用某种序列化器/反序列化器库,例如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}}

如需高级用法,请查看提供的链接。

希望能帮助到你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM