首页 > 编程语言 >python实战:使用json序列化

python实战:使用json序列化

时间:2024-02-20 22:13:08浏览次数:42  
标签:name python age 88 json score Tom 序列化

一,官方文档:

https://docs.python.org/zh-cn/3/library/json.html

二,json与字典的相互转化

1,字典转json字符串

1 2 3 4 5 6 7 import json   # 字典转json d = dict(name='Tom', age=2, score=88) json_d = json.dumps(d) print(type(json_d)) print(json_d)

运行结果:

<class 'str'>
{"name": "Tom", "age": 2, "score": 88}

2,json字符串转字典

1 2 3 4 5 6 7 import json   # json转字典 json_c = '{"name": "Tom", "age": 2, "score": 88}' c = json.loads(json_c) print(type(c)) print(c)

运行结果:

<class 'dict'>
{'name': 'Tom', 'age': 2, 'score': 88}

三,json与类实例的相互转化

1,通过dataclass把自定义类型的实例转为字典,再转为json

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import json from dataclasses import dataclass, asdict   @dataclass class Student:     name:str     age:int     score:int   s = Student('Tom', 2, 88) print(s)      # Student(name='Tom', age=2, score=88) # 将自定义类转换为字典 custom_dict = asdict(s) print(type(custom_dict))      # <class 'dict'> print(custom_dict)      # {'name': 'Tom', 'age': 2, 'score': 88} json_str = json.dumps(custom_dict) print(json_str)     # {"name": "Tom", "age": 2, "score": 88}

运行结果:

Student(name='Tom', age=2, score=88)
<class 'dict'>
{'name': 'Tom', 'age': 2, 'score': 88}
{"name": "Tom", "age": 2, "score": 88}

2,把实例通过__dict__转换为字典,再转为json

1 2 3 4 5 6 7 8 9 10 11 12 13 14 import json     class Student(object):     def __init__(self, name, age, score):         self.name = name         self.age = age         self.score = score   s = Student('Tom', 2, 88) json_s = json.dumps(s, default=lambda obj: obj.__dict__) print("__dict__转来的字典:",json_s)      # {"name": "Tom", "age": 2, "score": 88} json_s2 = json.dumps(s.__dict__) print("__dict__转来的字典2:",json_s)      # {"name": "Tom", "age": 2, "score": 88}

运行结果:

__dict__转来的字典: {"name": "Tom", "age": 2, "score": 88}
__dict__转来的字典2: {"name": "Tom", "age": 2, "score": 88}

3,通过定义函数把实例转为字典

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import json     class Student(object):     def __init__(self, name, age, score):         self.name = name         self.age = age         self.score = score   # 定义把类转为字典的函数 def student2dict(std):     return {         'name': std.name,         'age': std.age,         'score': std.score     }     s = Student('Tom', 2, 88) json_s = json.dumps(s, default=student2dict) print(json_s)

运行结果:

{"name": "Tom", "age": 2, "score": 88}

4,通过定义函数把字典转为实例

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import json     class Student(object):     def __init__(self, name, age, score):         self.name = name         self.age = age         self.score = score     def dict2student(d):     return Student(d['name'], d['age'], d['score'])     json_str = '{"name": "Tom", "age": 2, "score": 88}' stu = json.loads(json_str, object_hook=dict2student) print(stu)      # <__main__.Student object at 0x104ea9460> print(type(stu))      # <class '__main__.Student'>

运行结果:

<__main__.Student object at 0x104ea9460>
<class '__main__.Student'>

说明:刘宏缔的架构森林—专注it技术的博客,
网址:https://imgtouch.com
本文: https://blog.imgtouch.com/index.php/2024/02/20/shi-yong-json-xu-lie-hua/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: [email protected]

四,用json实现对象深拷贝

1,可以用json实现对对象的深拷贝

1 2 3 4 5 6 7 8 9 10 11 12 13 14 def deep_copy(obj):     # 将对象转换为 JSON 格式的字符串     obj_str = json.dumps(obj)       # 从 JSON 字符串中重新加载对象     new_obj = json.loads(obj_str)     return new_obj     # 测试 original_list = [1, 2, {'a': 'b'}] copied_list = deep_copy(original_list) print("原始列表:", original_list) print("复制后的列表:", copied_list)

运行结果:

原始列表: [1, 2, {'a': 'b'}]
复制后的列表: [1, 2, {'a': 'b'}]
   

标签:name,python,age,88,json,score,Tom,序列化
From: https://www.cnblogs.com/architectforest/p/18024153

相关文章

  • python中的内置函数zip函数
    关于zip()函数,有几点要讲的。首先,官方文档中,它是这样描述的:Makeaniteratorthataggregateselementsfromeachoftheiterables.Returnsaniteratoroftuples,wherethei-thtuplecontainsthei-thelementfromeachoftheargumentsequencesoriterables.The......
  • C#将string转成json并修改其中的值
    我想将一个json字符串中的某个字段值修改,然后重新转成新的json字符串。初始的json字符串如下:{deviceKey="gatewaydk",cmd="actionCall",service=new[]{new{siid=101,action=new{iid=2,......
  • python实战:用requests+做爬虫
    一,安装requests1,用pip安装(venv)liuhongdi@192news%pip3installrequests2,查看所安装库的版本:(venv)liuhongdi@192news%pip3showrequestsName:requestsVersion:2.31.0Summary:PythonHTTPforHumans.Home-page:https://requests.readthedocs.ioAu......
  • Python 实现Excel和CSV格式之间的互转
    通过使用Python编程语言,编写脚本来自动化Excel和CSV之间的转换过程,可以批量处理大量文件,定期更新数据,并集成转换过程到自动化工作流程中。本文将介绍如何使用第三方库Spire.XLSforPython实现:使用Python将Excel转为CSV使用Python将CSV转为Excel安装PythonExcel类库:pip......
  • python文件获取并读取固定长度数据实例解析
    一概念1file操作:文件操作一般有open,write,read,close几种,这里重点是read固定长度数据。read() 用于从文件读取指定的字节数,如果未给定或为负则读取所有。本文中心不在概念,直接上源码。二源码解析importsysfromPyQt5importQtWidgetsfromPyQt5.QtWidgetsimportQF......
  • rust结构体包含另一个结构体引用时,serde序列化问题
    代码如下useserde::{Deserialize,Serialize};#[derive(Serialize,Deserialize)]structPerson{id:String,name:String,}#[derive(Serialize,Deserialize)]structMsg<'a>{id:String,person:&'aPerson,}fnmain(){......
  • python不能跳转进入某个函数或模块的一种解决思路
    例如,下图中的get_bucket_mount_root函数可以顺利import进来,但是按ctrl键不能跳转进入这个函数: 一个解决思路是,在vscode终端中,打开python解释器,import上图中的hatbc库,然后用hatbc.__file__命令查找该库的__init__.py文件的路径,按住ctrl键,点击这个路径,即可跳转进入这个__init__.......
  • 解锁Mysql中的JSON数据类型,怎一个爽字了得
    引言在实际业务开发中,随着业务的变化,数据的复杂性和多样性不断增加。传统的关系型数据库模型在这种情况下会显得受限,因为它们需要预先定义严格的数据模式,并且通常只能存储具有相同结构的数据。而面对非结构化或半结构化数据的存储和处理需求,选择使用非关系型数据库或者创建子表存......
  • python · matplotlib | seaborn 画图与调整图例位置
    1seaborn画图代码存档:sns.set_style("whitegrid")#好看的styleplt.figure()#plt.plot(ppo_data['Step']*step_mul,ppo_data['ppo_mean'],label='PPO')#plt.plot(sac_data['Step']*step_mul,sac_data['sac_m......
  • [python] [mongoDB] pymongo -- 用python操作mongodb
    官方文档数据库格式mongodb采用了BSON格式,即database->collection->document,在python中,pymongo使用字典来表示一个documnet;document可以包含python原生的数据类型,比如datetime.datetime连接数据库MongoClient连接mongodb,读取数据库,集合和文档CRUD插入Collect......