2025-09-10:仓库迁移
This commit is contained in:
69
6.数据编码与处理/2.读写JSON数据.py
Normal file
69
6.数据编码与处理/2.读写JSON数据.py
Normal file
@@ -0,0 +1,69 @@
|
||||
import json
|
||||
from collections import OrderedDict
|
||||
|
||||
if __name__ == '__main__':
|
||||
# JSON是前后端传输里很常见的东西,很多数据要打成JSON字符串才能传输
|
||||
# 我们一般使用JSON.dumps和JSON.loads
|
||||
data = {
|
||||
"name": 'ACME',
|
||||
"shares": 100,
|
||||
"price": 542.33
|
||||
}
|
||||
|
||||
data_json = json.dumps(data)
|
||||
print(data_json)
|
||||
|
||||
data = json.loads(data_json)
|
||||
print(data)
|
||||
|
||||
# 但如果是同.json文件打交道,还是使用dump和load
|
||||
|
||||
# 在加载的时候,也可以把json对象载入成OrderedDict或Python对象
|
||||
data = json.loads(data_json, object_pairs_hook=OrderedDict)
|
||||
print(data)
|
||||
|
||||
class JsonObj:
|
||||
def __init__(self, transform_data):
|
||||
self.__dict__ = transform_data
|
||||
|
||||
data = json.loads(data_json, object_hook=JsonObj)
|
||||
print(data.name)
|
||||
|
||||
# 在转换为Json时,对象这个东西是无法直接被Json解析的,想要解析得把它转化成可以被序列化处理的字典
|
||||
# 我们可以实现一个解析器函数,将类的字段映射到字典里,load的时候再创建一个类把它反序列化出来
|
||||
|
||||
class Point:
|
||||
def __init__(self, x, y):
|
||||
self.x = x
|
||||
self.y = y
|
||||
|
||||
classes = {
|
||||
"Point": Point
|
||||
}
|
||||
|
||||
# 类->Json
|
||||
def serialize_instance(obj):
|
||||
d = {'__class__': type(obj).__name__}
|
||||
d.update(vars(obj))
|
||||
return d
|
||||
|
||||
# JsonStr->类
|
||||
def unserialize_instance(dic):
|
||||
cls_name = dic.pop('__class__', None)
|
||||
if cls_name:
|
||||
cls = classes[cls_name]
|
||||
obj = cls.__new__(cls)
|
||||
for k, v in dic.items():
|
||||
setattr(obj, k, v)
|
||||
return obj
|
||||
|
||||
else:
|
||||
return dic
|
||||
|
||||
p = Point(2, 3)
|
||||
s = json.dumps(p, default=serialize_instance)
|
||||
print(s)
|
||||
a = json.loads(s, object_hook=unserialize_instance)
|
||||
print(a.x, a.y)
|
||||
|
||||
|
Reference in New Issue
Block a user