赞
踩
json (JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率)
所谓序列化,就是python编码为json类型;反序列化,就是json解码为python类型。下文将会详细展开Python里这两种的具体函数:
1、序列化 - python编码为json类型
(1)json.dumps():把python数据类型转换成json字符串
- import json
-
- # 把python数据类型转换成json字符串
- dict_data = {'name': 'saxon', 'age': 18}
- print('dict_data', end = ':')
- print(dict_data)
- print('dict_data type',end = ':')
- print(type(dict_data))
- json_data = json.dumps(dict_data)
- print('json_data', end = ':')
- print(json_data)
- print('json_data type',end = ':')
- print(type(json_data))
输出:
(2)json.dump():把python数据类型转换成json字符串并存储在文件中
- import json
-
- # 把python数据类型转换成json字符串并存储在文件中
- dict_data = {'name': 'saxon', 'age': 18}
- with open('data/json_data.json', 'w') as f: # ‘w’表示写入文件,文件不存在则创建,存在则覆盖
- json.dump(dict_data, f)
- print("载入文件完成...")
- f.close()
输出:
2、反序列化 - json解码为python类型
(1)json.loads():解析json数据,返回python中的数据类型
- import json
-
- # 解析json数据,返回python中的数据类型
- json_data = '{"name": "saxon", "age": 18}'
- dict_data = json.loads(json_data)
- print('dict_data', end = ':')
- print(dict_data)
- print('dict_data type',end = ':')
- print(type(dict_data))
输出:
(2)json.load():打开json文件,解析json数据,返回python中的数据类型
- import json
-
- # 打开json文件,解析json数据,返回python中的数据类型
- with open('data/json_data.json','r') as f:
- dict_data = json.load(f)
- print("解析文件完成...")
- print('dict_data', end = ':')
- print(dict_data)
- print('dict_data type',end = ':')
- print(type(dict_data))
- f.close()
输出:
我们常用json文件来进行大规模的数据存储和处理,故良好的缩进格式会提升阅读效率,格式化输出的代码如下:
- import json
-
- # 格式化输出python数据类型到json文件
- dict_data = {'name': 'saxon', 'age': 18, 'hobby': ['basketball', 'football']}
- with open('data/json_data.json', 'w') as f:
- # f.write(json.dumps(dict_data, indent=4, ensure_ascii=False))
- json.dump(dict_data, f, indent=4, ensure_ascii=False)
- print("格式化输出完成...")
- f.close()
其中,indent=4设置json文件格式的缩进为4个空格,增加格式美观度;ensure_ascii=False指定不对非ASCII字符进行编码,直接输出中文至文件。
输出:
1、python类型编码为json类型转换对应表
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
2、json类型解码为python类型转换对应表
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。