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

相关文章

使用Python实现实时金价监控并自动提醒功能

《使用Python实现实时金价监控并自动提醒功能》在日常投资中,很多朋友喜欢在一些平台买点黄金,低买高卖赚点小差价,但黄金价格实时波动频繁,总是盯着手机太累了,于是我用Python写了一个实时金价监控... 目录工具能干啥?手把手教你用1、先装好这些"食材"2、代码实现讲解1. 用户输入参数2. 设置无头浏

一文教你如何解决Python开发总是import出错的问题

《一文教你如何解决Python开发总是import出错的问题》经常朋友碰到Python开发的过程中import包报错的问题,所以本文将和大家介绍一下可编辑安装(EditableInstall)模式,可... 目录摘要1. 可编辑安装(Editable Install)模式到底在解决什么问题?2. 原理3.

Python+wxPython构建图像编辑器

《Python+wxPython构建图像编辑器》图像编辑应用是学习GUI编程和图像处理的绝佳项目,本教程中,我们将使用wxPython,一个跨平台的PythonGUI工具包,构建一个简单的... 目录引言环境设置创建主窗口加载和显示图像实现绘制工具矩形绘制箭头绘制文字绘制临时绘制处理缩放和旋转缩放旋转保存编

Python 异步编程 asyncio简介及基本用法

《Python异步编程asyncio简介及基本用法》asyncio是Python的一个库,用于编写并发代码,使用协程、任务和Futures来处理I/O密集型和高延迟操作,本文给大家介绍Python... 目录1、asyncio是什么IO密集型任务特征2、怎么用1、基本用法2、关键字 async1、async

Python实现剪贴板历史管理器

《Python实现剪贴板历史管理器》在日常工作和编程中,剪贴板是我们使用最频繁的功能之一,本文将介绍如何使用Python和PyQt5开发一个功能强大的剪贴板历史管理器,感兴趣的可以了解下... 目录一、概述:为什么需要剪贴板历史管理二、功能特性全解析2.1 核心功能2.2 增强功能三、效果展示3.1 主界面

Python与Java交互出现乱码的问题解决

《Python与Java交互出现乱码的问题解决》在现代软件开发中,跨语言系统的集成已经成为日常工作的一部分,特别是当Python和Java之间进行交互时,编码问题往往会成为导致数据传输错误、乱码以及难... 目录背景:为什么会出现乱码问题产生的场景解决方案:确保统一的UTF-8编码完整代码示例总结在现代软件

Python+Tkinter实现Windows Hosts文件编辑管理工具

《Python+Tkinter实现WindowsHosts文件编辑管理工具》在日常开发和网络调试或科学上网场景中,Hosts文件修改是每个开发者都绕不开的必修课,本文将完整解析一个基于Python... 目录一、前言:为什么我们需要专业的Hosts管理工具二、工具核心功能全景图2.1 基础功能模块2.2 进

Python多重继承慎用的地方

《Python多重继承慎用的地方》多重继承也可能导致一些问题,本文主要介绍了Python多重继承慎用的地方,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录前言多重继承要慎用Mixin模式最后前言在python中,多重继承是一种强大的功能,它允许一个

python+OpenCV反投影图像的实现示例详解

《python+OpenCV反投影图像的实现示例详解》:本文主要介绍python+OpenCV反投影图像的实现示例详解,本文通过实例代码图文并茂的形式给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一、前言二、什么是反投影图像三、反投影图像的概念四、反向投影的工作原理一、利用反向投影backproj

Python中edge-tts实现便捷语音合成

《Python中edge-tts实现便捷语音合成》edge-tts是一个功能强大的Python库,支持多种语言和声音选项,本文主要介绍了Python中edge-tts实现便捷语音合成,具有一定的参考价... 目录安装与环境设置文本转语音查找音色更改语音参数生成音频与字幕总结edge-tts 是一个功能强大的