简体   繁体   中英

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. 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().

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.

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.

In that case I suggest you to use some kind of a serializer/deserializer library such as pydantic or marshmallow .

An example of your implementation in pydantic would look like this:

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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