json Deserialization of Python Objects

2023-12-15 00:28

本文主要是介绍json Deserialization of Python Objects,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

openweathermap.json


{"coord": {"lon": 114.0683, "lat":22.5455},"weather":[ {"id": 803, "main":"Clouds", "description":"多云", "icon":"04d"}],"base":"stations","main": {"temp": 299.1, "feels_like":299.1, "temp_min":296.39, "temp_max":300.29, "pressure":1018, "humidity":79, "sea_level":1018, "grnd_level":1017},"visibility":10000,"wind": {"speed": 2.73, "deg":137, "gust":3.32},"clouds": {"all": 82},"dt":1702530001,"sys": {"type": 2, "id":2031340, "country":"CN", "sunrise":1702508106, "sunset":1702546869},"timezone":28800,"id":1795565,"name":"Shenzhen","cod":200
}

# encoding: utf-8
# 版权所有 2023 涂聚文有限公司
# 许可信息查看:
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# Datetime  : 2023/12/14 22:14
# User      : geovindu
# Product   : PyCharm
# Project   : pyBaiduAi
# File      : Clouds.py
# explain   : 学习import json
import pickle
from typing import List
from typing import Any
from dataclasses import dataclass@dataclass
class Clouds:all: int@staticmethoddef from_dict(obj: Any) -> 'Clouds':_all = int(obj.get("all"))return Clouds(_all)@dataclass
class Coord:lon: float"""经度"""lat: float"""纬度"""@staticmethoddef from_dict(obj: Any) -> 'Coord':_lon = float(obj.get("lon"))_lat = float(obj.get("lat"))return Coord(_lon, _lat)@dataclass
class Main:""""""temp: float"""温度 """feels_like: floattemp_min: float"""最低温"""temp_max: float"""最高温"""pressure: inthumidity: int"""湿魔"""sea_level: intgrnd_level: int@staticmethoddef from_dict(obj: Any) -> 'Main':_temp = float(obj.get("temp"))_feels_like = float(obj.get("feels_like"))_temp_min = float(obj.get("temp_min"))_temp_max = float(obj.get("temp_max"))_pressure = int(obj.get("pressure"))_humidity = int(obj.get("humidity"))_sea_level = int(obj.get("sea_level"))_grnd_level = int(obj.get("grnd_level"))return Main(_temp, _feels_like, _temp_min, _temp_max, _pressure, _humidity, _sea_level, _grnd_level)@dataclass
class Sys:"""系统信息"""type: intid: intcountry: str"""所属国家"""sunrise: int"""日出时间戳"""sunset: int"""日落时间戳"""@staticmethoddef from_dict(obj: Any) -> 'Sys':_type = int(obj.get("type"))_id = int(obj.get("id"))_country = str(obj.get("country"))_sunrise = int(obj.get("sunrise"))_sunset = int(obj.get("sunset"))return Sys(_type, _id, _country, _sunrise, _sunset)@dataclass
class Weather:"""天气情况"""id: intmain: strdescription: str"""天气"""icon: str"""图标ID"""@staticmethoddef from_dict(obj: Any) -> 'Weather':_id = int(obj.get("id"))_main = str(obj.get("main"))_description = str(obj.get("description"))_icon = str(obj.get("icon"))return Weather(_id, _main, _description, _icon)@dataclass
class Wind:"""风况"""speed: float"""风速"""deg: intgust: float@staticmethoddef from_dict(obj: Any) -> 'Wind':_speed = float(obj.get("speed"))_deg = int(obj.get("deg"))_gust = float(obj.get("gust"))return Wind(_speed, _deg, _gust)@dataclass
class OpenWeather:""""天气类"""coord: Coordweather: List[Weather]base: strmain: Mainvisibility: intwind: Windclouds: Cloudsdt: intsys: Systimezone: intid: intname: strcod: int@staticmethoddef from_dict(obj: Any) -> 'OpenWeather':_coord = Coord.from_dict(obj.get("coord"))_weather = [Weather.from_dict(y) for y in obj.get("weather")]_base = str(obj.get("base"))_main = Main.from_dict(obj.get("main"))_visibility = int(obj.get("visibility"))_wind = Wind.from_dict(obj.get("wind"))_clouds = Clouds.from_dict(obj.get("clouds"))_dt = int(obj.get("dt"))_sys = Sys.from_dict(obj.get("sys"))_timezone = int(obj.get("timezone"))_id = int(obj.get("id"))_name = str(obj.get("name"))_cod = int(obj.get("cod"))return OpenWeather(_coord, _weather, _base, _main, _visibility, _wind, _clouds, _dt, _sys, _timezone, _id, _name, _cod)

调用:


import Model.Cloudsdef print_hi(name):# Use a breakpoint in the code line below to debug your script.print(f'Hi, {name} world,geovindu,涂聚文')  # Press Ctrl+F8 to toggle the breakpoint.# Press the green button in the gutter to run the script.
if __name__ == '__main__':print_hi('PyCharm,geovindu')#deserialization process:with open('openweathermap.json',encoding='utf-8') as json_file:data = json.load(json_file)print("data from file:")print(type(data))root=Model.Clouds.OpenWeather.from_dict(data)print(root)print("湿度",root.main.humidity)print("天气:", root.weather[0].description)

这篇关于json Deserialization of Python Objects的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/494436

相关文章

Java实现XML与JSON的互相转换详解

《Java实现XML与JSON的互相转换详解》这篇文章主要为大家详细介绍了如何使用Java实现XML与JSON的互相转换,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. XML转jsON1.1 代码目的1.2 代码实现2. JSON转XML3. JSON转XML并输出成指定的

利用Python实现添加或读取Excel公式

《利用Python实现添加或读取Excel公式》Excel公式是数据处理的核心工具,从简单的加减运算到复杂的逻辑判断,掌握基础语法是高效工作的起点,下面我们就来看看如何使用Python进行Excel公... 目录python Excel 库安装Python 在 Excel 中添加公式/函数Python 读取

Jackson库进行JSON 序列化时遇到了无限递归(Infinite Recursion)的问题及解决方案

《Jackson库进行JSON序列化时遇到了无限递归(InfiniteRecursion)的问题及解决方案》使用Jackson库进行JSON序列化时遇到了无限递归(InfiniteRecursi... 目录解决方案‌1. 使用 @jsonIgnore 忽略一个方向的引用2. 使用 @JsonManagedR

Python实现合并与拆分多个PDF文档中的指定页

《Python实现合并与拆分多个PDF文档中的指定页》这篇文章主要为大家详细介绍了如何使用Python实现将多个PDF文档中的指定页合并生成新的PDF以及拆分PDF,感兴趣的小伙伴可以参考一下... 安装所需要的库pip install PyPDF2 -i https://pypi.tuna.tsingh

基于Python开发批量提取Excel图片的小工具

《基于Python开发批量提取Excel图片的小工具》这篇文章主要为大家详细介绍了如何使用Python中的openpyxl库开发一个小工具,可以实现批量提取Excel图片,有需要的小伙伴可以参考一下... 目前有一个需求,就是批量读取当前目录下所有文件夹里的Excel文件,去获取出Excel文件中的图片,并

python中time模块的常用方法及应用详解

《python中time模块的常用方法及应用详解》在Python开发中,时间处理是绕不开的刚需场景,从性能计时到定时任务,从日志记录到数据同步,时间模块始终是开发者最得力的工具之一,本文将通过真实案例... 目录一、时间基石:time.time()典型场景:程序性能分析进阶技巧:结合上下文管理器实现自动计时

python中的整除向下取整的操作方法

《python中的整除向下取整的操作方法》Python中的//是整数除法运算符,用于执行向下取整的除法,返回商的整数部分,不会四舍五入,它在分治法、索引计算和整数运算中非常有用,本文给大家介绍pyth... 目录1. // 的基本用法2. // vs /(普通除法)3. // 在 mid = len(lis

基于Python和Tkinter实现高考倒计时功能

《基于Python和Tkinter实现高考倒计时功能》随着高考的临近,每个考生都在紧锣密鼓地复习,这时候,一款实用的倒计时软件能有效帮助你规划剩余时间,提醒你不要浪费每一分每一秒,今天,我们来聊聊一款... 目录一、软件概述:二、功能亮点:1. 高考倒计时2. 添加目标倒计时3. 励志语句4. 透明度调节与

Python如何查看数据的类型

《Python如何查看数据的类型》:本文主要介绍Python如何查看数据的类型方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录python查看数据的类型1. 使用 type()2. 使用 isinstance()3. 检查对象的 __class__ 属性4.

Python实现PDF与多种图片格式之间互转(PNG, JPG, BMP, EMF, SVG)

《Python实现PDF与多种图片格式之间互转(PNG,JPG,BMP,EMF,SVG)》PDF和图片是我们日常生活和工作中常用的文件格式,有时候,我们可能需要将PDF和图片进行格式互转来满足... 目录一、介绍二、安装python库三、Python实现多种图片格式转PDF1、单张图片转换为PDF2、多张图