簡體   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