1.前言
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。本文介绍如何使用json包编码和解码JSON对象。
2.主要函数
需要导入包import json
2.1 Python数据结构转换为JSON
案例1:将数组编码为 JSON 格式数据
import json
# Python 字典类型转换为 JSON 对象
data = {
'no' : 1,
'name' : 'Runoob',
'url' : 'http://www.runoob.com'
}
json_str = json.dumps(data)
#需要注意的是repr函数作用:将将对象转化为供解释器读取的形式。返回一个String类型
print ("Python 原始数据:", repr(data))
print ("JSON 对象:", json_str)
结果
Python 原始数据: {'no': 1, 'name': 'Runoob', 'url': 'http://www.runoob.com'}
JSON 对象: {"no": 1, "name": "Runoob", "url": "http://www.runoob.com"}
通过输出的结果可以看出,简单类型通过编码后跟其原始的repr()输出结果非常相似。
2.2 JSON编码的字符串转换回一个Python数据
案例2: JSON编码的字符串转换回一个Python数据:
import json
# Python 字典类型转换为 JSON 对象
data = {
'no' : 1,
'name' : 'Runoob',
'url' : 'http://www.runoob.com'
}
json_str = json.dumps(data)
#需要注意的是repr函数作用:将将对象转化为供解释器读取的形式。返回一个String类型
print ("Python 原始数据:", repr(data))
print ("JSON 对象:", json_str)
# 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str)
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])
结果:
Python 原始数据: {'no': 1, 'name': 'Runoob', 'url': 'http://www.runoob.com'}
JSON 对象: {"no": 1, "name": "Runoob", "url": "http://www.runoob.com"}
data2['name']: Runoob
data2['url']: http://www.runoob.com
2.3 写入、读取一个json文件
import json
# Python 字典类型转换为 JSON 对象
data = {
'no' : 1,
'name' : 'Runoob',
'url' : 'http://www.runoob.com'
}
json_str = json.dumps(data)
#需要注意的是repr函数作用:将将对象转化为供解释器读取的形式。返回一个String类型
print ("Python 原始数据:", repr(data))
print ("JSON 对象:", json_str)
# 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str)
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])
with open('data.json','w') as f:
json.dump(data, f)
with open('data.json','r') as f:
print(json.load(f))
结果
Python 原始数据: {'no': 1, 'name': 'Runoob', 'url': 'http://www.runoob.com'}
JSON 对象: {"no": 1, "name": "Runoob", "url": "http://www.runoob.com"}
data2['name']: Runoob
data2['url']: http://www.runoob.com
{'no': 1, 'name': 'Runoob', 'url': 'http://www.runoob.com'}