从0开始学python -59
创始人
2025-05-28 22:32:46

Python3 JSON 数据解析

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。

Python3 中可以使用 json 模块来对 JSON 数据进行编解码,它包含了两个函数:

  • json.dumps(): 对数据进行编码。
  • json.loads(): 对数据进行解码。

在 json 的编解码过程中,Python 的原始类型与 json 类型会相互转换,具体的转化对照如下:

Python 编码为 JSON 类型转换对应表:

PythonJSON
----------------------------------------
dictobject
--
list, tuplearray
strstring
int, float, int- & float-derived Enumsnumber
Truetrue
Falsefalse
Nonenull

JSON 解码为 Python 类型转换对应表:

JSONPython
----------------
objectdict
--
arraylist
stringstr
number (int)int
number (real)float
trueTrue
falseFalse
nullNone

json.dumps 与 json.loads 实例

以下实例演示了 Python 数据结构转换为JSON:

#!/usr/bin/python3import json# Python 字典类型转换为 JSON 对象
data = {'no' : 1,'name' : 'Runoob','url' : 'http://www.runoob.com'
}json_str = json.dumps(data)
print ("Python 原始数据:", repr(data))
print ("JSON 对象:", json_str)

执行以上代码输出结果为:

Python原始数据:{'url':'http://www.runoob.com','no':1,'name':'Runoob'}
JSON 对象:{"url":"http://www.runoob.com","no":1,"name":"Runoob"}

通过输出的结果可以看出,简单类型通过编码后跟其原始的repr()输出结果非常相似。

接着以上实例,我们可以将一个JSON编码的字符串转换回一个Python数据结构:

#!/usr/bin/python3import json# Python 字典类型转换为 JSON 对象
data1 = {'no' : 1,'name' : 'Runoob','url' : 'http://www.runoob.com'
}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'])

执行以上代码输出结果为:

Python原始数据:{'name':'Runoob','no':1,'url':'http://www.runoob.com'}
JSON 对象:{"name":"Runoob","no":1,"url":"http://www.runoob.com"}
data2['name']:Runoob
data2['url']:  http://www.runoob.com

如果你要处理的是文件而不是字符串,你可以使用 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

相关内容

热门资讯

于选择的英文作文【推荐6篇】 于选择的英文作文 篇一The Power of ChoiceChoice is a fundamen...
学校生活英语作文 学校生活英语作文(通用22篇)  在平平淡淡的日常中,许多人都有过写作文的经历,对作文都不陌生吧,作...
介绍家乡英语作文(精彩6篇) 介绍家乡英语作文 篇一My HometownI come from a small town cal...
阅读的英语作文Reading... 阅读的英语作文Reading 篇一The Importance of ReadingReading ...
优秀英语作文 优秀英语作文(通用34篇)  在日复一日的学习、工作或生活中,大家都尝试过写作文吧,作文一定要做到主...