使用Python解析JSON的实现示例 JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式.Python3 中可以使用 json 模块来对 JSON 数据进行编解码,主要包含了下面4个操作函数: 提示:所谓类文件对象指那些具有read()或者 write()方法的对象,例如,f = open('a.txt
JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。Python3 中可以使用 json 模块来对 JSON 数据进行编解码,主要包含了下面4个操作函数:
提示:所谓类文件对象指那些具有read()或者 write()方法的对象,例如,f = open('a.txt','r'),其中的f有read()方法,所以f就是类文件对象。
在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 |
操作示例 :
import json
data = {
'name': 'pengjunlee',
'age': 32,
'vip': True,
'address': {'province': 'GuangDong', 'city': 'ShenZhen'}
}
# 将 Python 字典类型转换为 JSON 对象
json_str = json.dumps(data)
print(json_str) # 结果 {"name": "pengjunlee", "age": 32, "vip": true, "address": {"province": "GuangDong", "city": "ShenZhen"}}
# 将 JSON 对象类型转换为 Python 字典
user_dic = json.loads(json_str)
print(user_dic['address']) # 结果 {'province': 'GuangDong', 'city': 'ShenZhen'}
# 将 Python 字典直接输出到文件
with open('pengjunlee.json', 'w', encoding='utf-8') as f:
json.dump(user_dic, f, ensure_ascii=False, indent=4)
# 将类文件对象中的JSON字符串直接转换成 Python 字典
with open('pengjunlee.json', 'r', encoding='utf-8') as f:
ret_dic = json.load(f)
print(type(ret_dic)) # 结果 <class 'dict'>
print(ret_dic['name']) # 结果 pengjunlee
注意:使用eval()能够实现简单的字符串和Python类型的转化。
user1 = eval('{"name":"pengjunlee"}')
print(user1['name']) # 结果 pengjunlee
到此这篇关于使用Python解析JSON的实现示例的文章就介绍到这了,更多相关Python解析JSON内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
本文标题为:使用Python解析JSON的实现示例


基础教程推荐
- 创建python虚拟环境(在ubuntu16.04中) 2023-09-04
- linux 安装 python3 2023-09-03
- python验证多组数据之间有无显著差异 2023-08-08
- 云服务器Ubuntu更改默认python版本 2023-09-03
- Python爬虫爬取属于自己的地铁线路图 2023-08-05
- 远程和Ubuntu服务器进行Socket通信,使用python和C#(准备篇) 2023-09-05
- MySQL数据优化-多层索引 2023-08-11
- Python+OpenCV实战之实现文档扫描 2022-10-20
- windows下面使用多版本Python安装指定版本的虚拟环境 2023-09-04
- 使用Pycharm创建一个Django项目的超详细图文教程 2022-09-02