使用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的实现示例


基础教程推荐
- Centos7下安装python环境 2023-09-04
- ubuntu 18 python3.6 的安装与 python2的版本切换 2023-09-03
- Python 中 Elias Delta 编码详情 2023-08-08
- CentOS 7.5 安装 Python3.7 2023-09-03
- centos系统 anaconda3(python3)安装pygrib 2023-09-04
- 基于Python实现股票数据分析的可视化 2023-08-04
- python的环境conda简介 2022-10-20
- Python爬取当网书籍数据并数据可视化展示 2023-08-11
- Python基础学习之函数和代码复用详解 2022-09-02
- 四步教你学会打包一个新的Python模块 2022-10-20