学习目标:
1、序列化?
答:程序中的各种数据对象 变成 表示该数据对象的 字节串 这个过程就叫序列化。
2、反序列化?
答:字节串转化为 程序中的数据对象 这个过程 称之为 反序列化
3、对象 json深拷贝?
答:拷贝的对象地址都不一样。
代码块学习:
序列化:
# 导入json
import json
historyTransactions = [
{
'time' : '20170101070311', # 交易时间
'amount' : '3088', # 交易金额
'productid' : '45454455555', # 货号
'productname' : 'iphone7' # 货名
},
{
'time' : '20170101050311', # 交易时间
'amount' : '18', # 交易金额
'productid' : '453455772955', # 货号
'productname' : '奥妙洗衣液' # 货名
},
]
# dumps(格式化的变量名)
# ensure_ascii=False 如果没有这个参数,得到的json中文字就会以Unicode的显示
# indent=4 缩进打印
# 序列化 :程序的各种类型数据对象 变成 表示该数据对象的 字节串
object_json = json.dumps(historyTransactions,ensure_ascii=False,indent=4)
print(object_json)
print(type(object_json)) # <class 'str'>
反序列化:
import json
historyTransactions = [
{
'time' : '20170101070311', # 交易时间
'amount' : '3088', # 交易金额
'productid' : '45454455555', # 货号
'productname' : 'iphone7' # 货名
},
{
'time' : '20170101050311', # 交易时间
'amount' : '18', # 交易金额
'productid' : '453455772955', # 货号
'productname' : '奥妙洗衣液' # 货名
},
]
# 序列化
obj_json = json.dumps(historyTransactions,ensure_ascii=False,indent=4)
print(type(obj_json)) # <class 'str'>
print(obj_json)
# 反序列化
object_List = json.loads(obj_json)
print(type(object_List)) # <class 'list'>
print(object_List)
对象深拷贝:
list1 = [
{
'name':'yuerwen',
'age':18,
'height':188
},
{
'name':'haisliu',
'age':18,
'height':166
}
]
# list2 = list1
# 深拷贝
'''
l = []
for one in list1:
l.append({'name':one['name'],'height':one['height']})
# print(l[0]['name'] )
list1[0]['name'] = 'ddd'
print(l[0]['name'])
'''
# 使用json的 深拷贝
import json
new_list1 = json.loads(json.dumps(list1,ensure_ascii=False))
list1[0]['name'] = 'ddd'
print(new_list1[0]['name']) # yuerwen