Python3 教程
- 第1节:Python3 简介
- 第2节:Python3 安装
- 第3节:Python3 使用上手
- 第4节:Python3 解释器
- 第5节:Python3 VSCode 配置
- 第6节:Python3 基础语法
- 第7节:Python3 编程第一步
- 第8节:Python3 基本数据类型
- 第9节:Python3 注释
- 第10节:Python3 运算符
- 第11节:Python3 数字
- 第12节:Python3 序列
- 第13节:Python3 字符串
- 第14节:Python3 列表
- 第15节:Python3 元组
- 第16节:Python3 字典
- 第17节:Python3 集合
- 第18节:Python3 条件控制
- 第19节:Python3 循环
- 第20节:Python3 迭代器与生成器
- 第21节:Python3 函数
- 第22节:Python3 数据结构
- 第23节:Python3 模块
- 第24节:Python3 输入和输出
- 第25节:Python3 File 方法
- 第26节:Python3 OS 文件/目录方法
- 第27节:Python3 错误和异常
- 第28节:Python3 面向对象
- 第29节:Python3 标准库概览
- 第30节:Python3 正则表达式
- 第31节:Python3 CGI 编程
- 第32节:Python3 MySQL 数据库连接
- 第33节:Python3 网络编程
- 第34节:Python3 SMTP发送邮件
- 第35节:Python3 多线程
- 第36节:Python3 XML解析
- 第37节:Python3 JSON 数据解析
- 第38节:Python3 日期和时间
- 第39节:Python3 内置函数
- 第40节:Python3 MongoDB
- 第41节:Python3 urllib模块
- 第42节:Python3 uWSGI 安装配置
- 第43节:Python3 pip
- 第44节:Python3 operator 模块
- 第45节:Python3 math 模块
- 第46节:Python3 requests 模块
- 第47节:Python3 random 模块
Python3 JSON 数据解析
JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于 ECMAScript 的一个子集。
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 实例
以下实例演示了 Python 数据结构转换为 JSON:
#!/usr/bin/python3
import json
# Python 字典类型转换为 JSON 对象
data = {
'no' : 1,
'name' : 'test',
'url' : 'http://www.test.cn'
}
json_str = json.dumps(data)
print ("Python 原始数据:", repr(data))
print ("JSON 对象:", json_str)
执行以上代码输出结果为:
Python 原始数据: {'url': 'http://www.test.cn', 'no': 1, 'name': 'test'}
JSON 对象: {"url": "http://www.test.cn", "no": 1, "name": "test"}
通过输出的结果可以看出,简单类型通过编码后跟其原始的repr()输出结果非常相似。
接着以上实例,我们可以将一个JSON编码的字符串转换回一个Python数据结构:
#!/usr/bin/python3
import json
# Python 字典类型转换为 JSON 对象
data1 = {
'no' : 1,
'name' : 'test',
'url' : 'http://www.test.cn'
}
json_str = json.dumps(data1)
print ("Python 原始数据:", repr(data1))
print ("JSON 对象:", json_str)
# 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str)
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])
执行以上代码输出结果为:
ython 原始数据: {'name': 'test', 'no': 1, 'url': 'http://www.test.cn'}
JSON 对象: {"name": "test", "no": 1, "url": "http://www.test.cn"}
data2['name']: test
data2['url']: http://www.test.cn
如果你要处理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 来编码和解码 JSON 数据。例如:
# 写入 JSON 数据
with open('data.json', 'w') as f:
json.dump(data, f)
# 读取数据
with open('data.json', 'r') as f:
data = json.load(f)
更多资料请参考:https://docs.python.org/3/library/json.html