简体   繁体   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?

I have the following issue.我有以下问题。 I want to convert a complex object to a json dictionary.我想将复杂对象转换为 json 字典。 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().我无法直接执行此操作,因此我最终使用 json.dumps() 先将对象转换为字符串,然后使用 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.我希望能够使用 json.dump() 来做到这一点,但是这要求我将它放入一个类似文件的对象中,当想要获得 dict 数据结构时,这似乎是一个额外的圈套。

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)

So after clarifying your requirements, it seems like you would like to convert an arbitrary class to a nested dict and not to a JSON string.因此,在澄清您的要求之后,您似乎想将任意class转换为嵌套的dict而不是 JSON 字符串。

In that case I suggest you to use some kind of a serializer/deserializer library such as pydantic or marshmallow .在这种情况下,我建议您使用某种序列化器/反序列化器库,例如pydanticmarshmallow

An example of your implementation in pydantic would look like this:您在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}}

For advanced usage please check out the provided links.如需高级用法,请查看提供的链接。

Hope it helps!希望能帮助到你!

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

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