Python Json序列化与反序列化的示例

不同的编程语言有不同的数据类型; 比如说:

Python的数据类型有(dict、list、string、int、float、long、bool、None)
Java的数据类型有(bool、char、byte、short、int、long、float、double)
C的数据类型有(bit、bool、char、int、short、long、unsigned、double、float)
Tcl的数据类型(int、bool、float、string)
Ruby的数据类型(Number、String、Ranges、Symbols、true、false、Array、Hash)
...

他们的共同特点是,都有字符串类型!

所以要实现不同的编程语言之间对象的传递,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。
JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便.

JSON类型     Python类型
{}                  dict
[]                  list
"string"            str
1234.56             int或float
true                True
false               False
null                None

在python中,序列化可以理解为:把python的对象编码转换为json格式的字符串,反序列化可以理解为:把json格式字符串解码为python数据对象。在python的标准库中,专门提供了json库与pickle库来处理这部分。

json的dumps方法和loads方法,可实现数据的序列化和反序列化。具体来说,dumps方法,可将json格式数据序列为Python的相关的数据类型;loads方法则是相反,把python数据类型转换为json相应的数据类型格式要求。在序列化时,中文汉字总是被转换为unicode码,在dumps函数中添加参数ensure_ascii=False即可解决。

下面是json的序列化与反序列化:

1、Json序列化如下:

import json
print (json.__all__)  #查看json库的所有方法
['dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONEncoder']

未在dumps函数中添加参数ensure_ascii=False,结果如下:

#coding: utf-8
import json
dict = {'name':'zhangsan', 'age':33, 'address':'红星路'}
print('未序列化前的数据类型为:', type(dict))
print('为序列化前的数据:', dict)
#对dict进行序列化的处理
dict_xu = json.dumps(dict)  #直接进行序列化
print('序列化后的数据类型为:', type(dict_xu))
print('序列化后的数据为:', dict_xu)

未序列化前的数据类型为: <class 'dict'>
为序列化前的数据: {'name': 'zhangsan', 'address': '红星路', 'age': 33}
序列化后的数据类型为: <class 'str'>
序列化后的数据为: {"name": "zhangsan", "address": "\u7ea2\u661f\u8def", "age": 33}

在dumps函数中添加参数ensure_ascii=False,结果如下:

#coding: utf-8
import json

dict = {'name':'zhangsan', 'age':33, 'address':'红星路'}
print('未序列化前的数据类型为:', type(dict))
print('为序列化前的数据:', dict)
#对dict进行序列化的处理
dict_xu = json.dumps(dict,ensure_ascii=False)  #添加ensure_ascii=False进行序列化
print('序列化后的数据类型为:', type(dict_xu))
print('序列化后的数据为:', dict_xu)

未序列化前的数据类型为: <class 'dict'>
为序列化前的数据: {'address': '红星路', 'age': 33, 'name': 'zhangsan'}
序列化后的数据类型为: <class 'str'>
序列化后的数据为: {"address": "红星路", "age": 33, "name": "zhangsan"}

2、Json反序列化如下:

#coding: utf-8
import json
dict = {'name':'zhangsan', 'age':33, 'address':'红星路'}
print('未序列化前的数据类型为:', type(dict))
print('为序列化前的数据:', dict)
#对dict进行序列化的处理
dict_xu = json.dumps(dict,ensure_ascii=False)  #添加ensure_ascii=False进行序列化
print('序列化后的数据类型为:', type(dict_xu))
print('序列化后的数据为:', dict_xu)
#对dict_xu进行反序列化处理
dict_fan = json.loads(dict_xu)
print('反序列化后的数据类型为:', type(dict_fan))
print('反序列化后的数据为: ', dict_fan)

未序列化前的数据类型为: <class 'dict'>
为序列化前的数据: {'name': 'zhangsan', 'age': 33, 'address': '红星路'}
序列化后的数据类型为: <class 'str'>
序列化后的数据为: {"name": "zhangsan", "age": 33, "address": "红星路"}
反序列化后的数据类型为: <class 'dict'>
反序列化后的数据为:  {'name': 'zhangsan', 'age': 33, 'address': '红星路'}

在实际的工作中,序列化或者反序列化的可能是一个文件的形式,不可能像如上写的那样简单的,下来就来实现这部分,把文件内容进行序列化和反序列化,先来看序列化的代码,两步操作:1、先序列化 列表对象 ;2、步把序列化成的字符串写入文件:

#coding: utf-8
import json

list = ['Apple','Huawei','selenium','java','python']
#把list先序列化,写入到一个文件中
# 两步操作 1步先序列化 列表对象 2步把序列化成的字符串写入文件
json.dump(list, open('e:/test.txt','w'))  
r1=open('e:/test.txt','r')
print(r1.read())

["Apple", "Huawei", "selenium", "java", "python"]

反序列化,两步操作:1、先读取文件的字符串对象;2、然后反序列化成列表对象:

#coding: utf-8
import json

list = ['Apple','Huawei','selenium','java','python']
#把list先序列化,写入到一个文件中
# 两步操作 1步先序列化 列表对象 2步把序列化成的字符串写入文件
json.dump(list, open('e:/test.txt','w'))  
r1=open('e:/test.txt','r')
print(r1.read())
#------------------------------------------------------------
#两步操作:1、先读取文件的字符串对象;2、然后反序列化成列表对象
res=json.load(open('e:/test.txt','r'))
print (res)
print('数据类型:',type(res))

["Apple", "Huawei", "selenium", "java", "python"]
['Apple', 'Huawei', 'selenium', 'java', 'python']
数据类型: <class 'list'>

相关推荐