学习Python中如何读写JSON文件。
介绍
JSON在python中分别由list和dict组成。
json模块和pickle模块是常用的两个序列化模块。
json: 用于字符串和python数据类型间进行转换
pickle:用于python特有的类型和python的数据类型间进行转换
json模块与pickle模块都提供dumps
、dump
、loads
、load
四种方法
dumps
把数据类型转换成字符串
dump
把数据类型转换成字符串并存储在文件中
loads
把字符串转换成数据类型
load
把文件打开从字符串转换成数据类型
json是可以在不同语言之间交换数据的,而pickle只在python之间使用。json只能序列化最基本的数据类型,josn只能把常用的数据类型序列化(列表、字典、列表、字符串、数字、),比如日期格式、类对象!josn就不行了。而pickle可以序列化所有的数据类型,包括类,函数都可以序列化。
方法
dumps
import json
test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]}
print(test_dict)
print(type(test_dict))
#dumps 将数据转换成字符串
json_str = json.dumps(test_dict)
print(json_str)
print(type(json_str))
输出
{'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]}
<class 'dict'>
{"bigberg": [7600, {"1": [["iPhone", 6300], ["Bike", 800], ["shirt", 300]]}]}
<class 'str'>
loads
import json
test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]}
print(test_dict)
print(type(test_dict))
#dumps 将数据转换成字符串
json_str = json.dumps(test_dict)
#loads 将字符串转换为字典
new_dict = json.loads(json_str)
print(new_dict)
print(type(new_dict))
输出
{"bigberg": [7600, {"1": [["iPhone", 6300], ["Bike", 800], ["shirt", 300]]}]}
<class 'str'>
{'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]}
<class 'dict'>
dump
import json
test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]}
with open("data.json","w") as f:
json.dump(test_dict,f)
print("加载入文件完成...")
读取Json文件
import json
with open("data.json",'r+') as f:
load_dict = json.load(f)
print(load_dict)
写入Json文件
import json
data = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]}
with open("data.json","w+") as f:
json.dump(data,f)