python读取json文件
正文
- 序列化和反序列化
- 对象深拷贝
一般而言,我们把 程序的各种类型数据对象 变成 表示该数据对象的 字节串 这个过程 称之为 序列化 。
而把 字节串转化为 程序中的数据对象 这个过程 称之为 反序列化
序列化
将数据对象序列化为 json格式的字符串,就可以使用该库里面的dumps函数,如下
import json historyTransactions = [ { 'time' : '20170101070311', # 交易时间 'amount' : '3088', # 交易金额 'productid' : '45454455555', # 货号 'productname' : 'iphone7' # 货名 }, { 'time' : '20170101050311', # 交易时间 'amount' : '18', # 交易金额 'productid' : '453455772955', # 货号 'productname' : '奥妙洗衣液' # 货名 } ] # dumps 方法将数据对象序列化为 json格式的字符串 jsonstr = json.dumps(historyTransactions) print(jsonstr)
输出结果
[{"time": "20170101070311", "amount": "3088", "productid": "45454455555", "productname": "iphone7"}, {"time": "20170101050311", "amount": "18", "productid": "453455772955", "productname": "\u5965\u5999\u6d17\u8863\u6db2"}]
json.dumps 方法发现将字符串中如果有非ascii码字符,比如中文‘奥妙洗衣液’, 缺省就用该字符的unicode数字来表示。
若不想显示为unicode,可以给参数 ensure_ascii 赋值为 False
json.dumps(historyTransactions,ensure_ascii=False,indent=4) # indent参数表示转换后缩进为4
改完后再运行下,结果就变成了这样
[ { "time": "20170101070311", "amount": "3088", "productid": "45454455555", "productname": "iphone7" }, { "time": "20170101050311", "amount": "18", "productid": "453455772955", "productname": "奥妙洗衣液" } ]
反序列化
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'>
对象深拷贝
team1 =[ { 'name':'乔丹', 'height':198 }, { 'name':"姚明', 'height':223 } ] # 这个方式不行,因为添加的仍然是team1的元素 team = [] for one in team1: team2.append(one) # team2.append({'name':one['name'],'height':one['height']}) # 可行但麻烦 team2[0]['name'] = '麦迪' print(team1[0]['name']) import json team2 = json.loads(dumps(team1)) # 利用json进行深拷贝
参考学习:https://www.byhy.net/tut/py/extra/json/

浙公网安备 33010602011771号