序列化:将对象的状态信息转换为可以存储或可以通过网络传输的过程,传输的格式可以是json,xml。
反序列化:就是从存储区域(json,xml)读取反序列化对象的状态,重新创建该对象
Json:一种轻量级数据交互格式,相对于XML更简单,也易于阅读和编写,机器方便解析和生成,json是JavaScript中的一个子集
Python3 中可以使用 json 模块来对 JSON 数据进行编解码,它包含了两个函数:
- json.dumps(): 对数据进行编码。
- json.loads(): 对数据进行解码。
在json的编解码过程中,python 的原始类型与json类型会相互转换,具体的转化对照如下:
Python 编码为 JSON 类型转换对应表:
python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
JSON 解码为 Python 类型转换对应表:
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
json.dumps 与 json.loads 实例
1、以下实例演示了 Python 数据结构转换为JSON:
1 ''' 2 Author:Ranxf 3 ''' 4 5 import json 6 7 # python 字典类型转换为JSON对象 8 data = { 9 "type": "create", # 同步用户消息类型 10 "username": "X012", # 用户名(唯一标识,需保存) 11 "password": "4875c0fa1cc0113b91a504aaff70", # MD5后用户密码(需保存) 12 "createTime": "2017-07-17 14:00:10.771", # 用户创建时间(需保存) 13 "lastLoginTime": "2017-07-17 14:00:10.771", # 最后登陆时间 14 "name": "test", # 姓名(需保存) 15 "description": "", # 描述 16 "policeNumber": "9257", # 警号(需保存) 17 "phoneNumber": "13000000000", # 联系方式 18 "organizationName": "testorganization", # 所属组织 19 "status": "1", # 用户状态(0:正常 1:禁用 ,需保存) 20 "timeStamp": "2017-07-17 14:00:10.771", # 操作时间 21 # "roles": ["XZ_ADMIN", "XZ_BUSINESS"] # 角色代码(需保存) 22 "roles": ["XZ_BUSINESS"] # 角色代码(需保存) 23 } 24 25 json_str = json.dumps(data) 26 print("python 原始数据: ", repr(data)) 27 print("Json 对象: ", json_str)
运行结果:
python 原始数据: {'timeStamp': '2017-07-17xa014:00:10.771', 'roles': ['XZ_BUSINESS'], 'policeNumber': '9257', 'name': 'test', 'type': 'create', 'password': '4875c0fa1cc0113b91a504aaff70', 'phoneNumber': '137875422489', 'lastLoginTime': '2017-07-17 14:00:10.771', 'status': '1', 'organizationName': 'testorganization', 'username': 'X012', 'description': '', 'createTime': '2017-07-17 14:00:10.771'}
Json 对象: {"timeStamp": "2017-07-17u00a014:00:10.771", "roles": ["XZ_BUSINESS"], "policeNumber": "9257", "name": "test", "type": "create", "password": "4875c0fa1cc0113b91a504aaff70", "phoneNumber": "137875422489", "lastLoginTime": "2017-07-17 14:00:10.771", "status": "1", "organizationName": "testorganization", "username": "X012", "description": "", "createTime": "2017-07-17 14:00:10.771"}
Process finished with exit code 0
2、将一个Json编码的字符串转回一个Python数据结构:
1 ''' 2 Author:Ranxf 3 ''' 4 5 import json 6 7 # python 字典类型转换为JSON对象 8 data = { 9 "type": "create", # 同步用户消息类型 10 "username": "X012", # 用户名(唯一标识,需保存) 11 "password": "4875c0fa1cc0113b91a504aaff70", # MD5后用户密码(需保存) 12 "createTime": "2017-07-17 14:00:10.771", # 用户创建时间(需保存) 13 "lastLoginTime": "2017-07-17 14:00:10.771", # 最后登陆时间 14 "name": "测试人", # 姓名(需保存) 15 "description": "", # 描述 16 "policeNumber": "9257", # 警号(需保存) 17 "phoneNumber": "13000000000", # 联系方式 18 "organizationName": "测试组织", # 所属组织 19 "status": "1", # 用户状态(0:正常 1:禁用 ,需保存) 20 "timeStamp": "2017-07-17 14:00:10.771", # 操作时间 21 # "roles": ["XZ_ADMIN", "XZ_BUSINESS"] # 角色代码(需保存) 22 "roles": ["XZ_BUSINESS"] # 角色代码(需保存) 23 } 24 25 json_str = json.dumps(data) 26 print("python 原始数据: ", repr(data)) 27 print("Json 对象: ", json_str) 28 29 # 将json对象转换为Python字典 30 data2 = json.loads(json_str) 31 print("data2['neme']: ", data2['name']) 32 print("data2['organizationName']: ", data2['organizationName'])
运行结果:
/usr/bin/python3.5 /media/ranxf/13ea76aa-89fc-4228-8e84-40e5707bc91b/python3_1000/1000/python3_server/python3_json/learn_json.py
python 原始数据: {'timeStamp': '2017-07-17xa014:00:10.771', 'policeNumber': '9257', 'createTime': '2017-07-17 14:00:10.771', 'username': 'X012', 'roles': ['XZ_BUSINESS'], 'description': '', 'password': '4875c0fa1cc0113b91a504aaff70', 'organizationName': '测试组织', 'phoneNumber': '13000000000', 'status': '1', 'type': 'create', 'lastLoginTime': '2017-07-17 14:00:10.771', 'name': '测试人'}
Json 对象: {"timeStamp": "2017-07-17u00a014:00:10.771", "policeNumber": "9257", "createTime": "2017-07-17 14:00:10.771", "username": "X012", "roles": ["XZ_BUSINESS"], "description": "", "password": "4875c0fa1cc0113b91a504aaff70", "organizationName": "u6d4bu8bd5u7ec4u7ec7", "phoneNumber": "13000000000", "status": "1", "type": "create", "lastLoginTime": "2017-07-17 14:00:10.771", "name": "u6d4bu8bd5u4eba"}
data2['neme']: 测试人
data2['organizationName']: 测试组织
注意该Python原始数据中有中文,在转换为json对象后,输出显示为Unicode编码"organizationName": "u6d4bu8bd5u7ec4u7ec7","name": "u6d4bu8bd5u4eba"
解决这个问题的办法:
代码 json_str = json.dumps(data) 变为: json_str = json.dumps(data, ensure_ascii=False)
3、如果需要处理的是文件而不是字符串,使用json.dump() 和 json.load() 来编码和解码JSON数据。例如:
''' Author:Ranxf ''' import json data = { "type": "create", # 同步用户消息类型 "username": "X012", # 用户名(唯一标识,需保存) "password": "4875c0fa1cc0113b91a504aaff70", # MD5后用户密码(需保存) "createTime": "2017-07-17 14:00:10.771", # 用户创建时间(需保存) "lastLoginTime": "2017-07-17 14:00:10.771", # 最后登陆时间 "name": "测试人", # 姓名(需保存) "description": "", # 描述 "policeNumber": "9257", # 警号(需保存) "phoneNumber": "13000000000", # 联系方式 "organizationName": "测试组织", # 所属组织 "status": "1", # 用户状态(0:正常 1:禁用 ,需保存) "timeStamp": "2017-07-17 14:00:10.771", # 操作时间 # "roles": ["XZ_ADMIN", "XZ_BUSINESS"] # 角色代码(需保存) "roles": ["XZ_BUSINESS"] # 角色代码(需保存) } with open('data1.json', 'w') as f: json.dump(data, f, ensure_ascii=False) # 读取数据 with open('data.json', 'r') as f: data = json.load(f) print(data)
写入如果不加(, ensure_ascii=False)数据运行结果:
{"type": "create", "organizationName": "u6d4bu8bd5u7ec4u7ec7", "password": "4875c0fa1cc0113b91a504aaff70", "description": "", "policeNumber": "9257", "phoneNumber": "13000000000", "lastLoginTime": "2017-07-17 14:00:10.771", "timeStamp": "2017-07-17u00a014:00:10.771", "status": "1", "name": "u6d4bu8bd5u4eba", "username": "X012", "createTime": "2017-07-17 14:00:10.771", "roles": ["XZ_BUSINESS"]}
加入代码中json.dump(data, f, ensure_ascii=False)下划线部分,写入data.json的数据为:
{"createTime": "2017-07-17 14:00:10.771", "policeNumber": "9257", "timeStamp": "2017-07-17 14:00:10.771", "username": "X012", "password": "4875c0fa1cc0113b91a504aaff70", "roles": ["XZ_BUSINESS"], "organizationName": "测试组织", "description": "", "phoneNumber": "13000000000", "lastLoginTime": "2017-07-17 14:00:10.771", "type": "create", "name": "测试人", "status": "1"}
以上运行结果主要看中文字段区别即可(一个是unicode显示,一个中utf8显示)
参考:
https://docs.python.org/3/library/json.html
http://www.runoob.com/python3/python3-json.html