1. 序列化

json这个库,可以 方便的把内置的数据对象 序列化为json格式文本的字符串。

# 序列化
"""
json格式:字符串只能用双引号,列表最后一个元素后面不能有逗号
数据对象序列化为json格式的字符串,就可以使用该库里面的dumps函数进行序列化。
序列化后的结果,是一个字符串。 json格式本身就是一个字符串。
"""
import json
historyTransactions = [

{
'time' : '20170101070311', # 交易时间
'amount' : '3088', # 交易金额
'productid' : '45454455555', # 货号
'productname' : 'iphone7' # 货名
},
{
'time' : '20170101050311', # 交易时间
'amount' : '18', # 交易金额
'productid' : '453455772955', # 货号
'productname' : '奥妙洗衣液' # 货名
}

]

# dumps 方法将数据对象序列化为 json格式的字符串
jsonstr = json.dumps(historyTransactions,ensure_ascii=False,indent=4)
print(jsonstr)
print(type(jsonstr))
[
{
"time": "20170101070311",
"amount": "3088",
"productid": "45454455555",
"productname": "iphone7"
},
{
"time": "20170101050311",
"amount": "18",
"productid": "453455772955",
"productname": "奥妙洗衣液"
}
]
<class 'str'>

2. 反序列化

# 反序列化
"""
接收方如果也是Python开发的,可以使用 json库中的 loads方法,把json格式的字符串变为 Python中的数据对象。

"""
import json
jsonstr = '[{"time": "20170101070311", "amount": "3088", "productid": "45454455555", "productname": "iphone7"}, {"time": "20170101050311", "amount": "18", "productid": "453455772955", "productname": "\u5965\u5999\u6d17\u8863\u6db2"}]'

translist = json.loads(jsonstr)
print(translist)
print(type(translist))
[{'time': '20170101070311', 'amount': '3088', 'productid': '45454455555', 'productname': 'iphone7'}, {'time': '20170101050311', 'amount': '18', 'productid': '453455772955', 'productname': '奥妙洗衣液'}]
<class 'list'>

3. 深浅拷贝

3.1浅度拷贝

"""
复制字典dict数据的时候,不能直接复制。因为复制的话,如果要修改复制后的dict,那么复制前的dict也会变。
常规的复制(拷贝),也叫浅拷贝。
"""
team1 = [
{
'name':"qiao dan",
'height':198
},
{
'name':"rao ming",
'height':223
}
]

team2 = []
for one in team1:
team2.append(one)
team2[0]['name'] = '麦迪'

# 可以看到,修改了team2,team1也改变了
print(team1[0]['name'] )

3.2 深度拷贝

# 使用深度拷贝:实现修改了team2之后,team1不会改变。
import json

team1 = [
{
'name':"qiao dan",
'height':198
},
{
'name':"rao ming",
'height':223
}
]


team2 = json.loads(json.dumps(team1))


team2[0]['name'] = '麦迪'

# 可以看到,修改了team2,team1没有改变了
print(team1[0]['name'] )