python--JSON

学习目标:
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yuerwen_python

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值