我们把 程序的各种类型数据对象 变成 表示该数据对象的 字节串 这个过程 称之为 序列化 。
而把 字节串转化为 程序中的数据对象 这个过程 称之为 反序列化
序列化
要把数据对象序列化为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)
json.dumps 方法发现将字符串中如果有非ascii码字符,比如中文, 缺省就用该字符的unicode数字来表示。
比如 奥
的unicode是 5965, 就表示为 \u5965
如果你不想这样,可以给参数 ensure_ascii 赋值为 False,如下所示
json.dumps(historyTransactions,ensure_ascii=False,indent=4)
其中,indent参数表示转换后缩进为4,这样显得整洁好看,
反序列化
使用 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))