JSON:是一种轻量级的数据交换格式。Python中包含了json模块来对JSON进行编解码。
功能:主要应用的两个函数为:
json.dumps(): 对数据进行编码。
json.loads(): 对数据进行解码。
在json的编解码过程中,python的原始类型会与json类型进行相互转换。
格式:
import json
data={
‘pluno‘:‘131001‘,
‘pluname‘:‘egg‘,
‘price‘:‘4.98‘,
‘qty‘:‘100‘
}
filename=‘txt_files/data.json‘
#open()函数中,第一个参数(filename),是要把数据保存到txt_files目录下,新建文件data.json格式
with open(filename,‘w‘) as file1:
# json.dump(),参数data,是要保存的数据(上面的data字典),file1,表示要保存到的文件(data.json)
json.dump(data,file1)
file1.write(‘\n‘)
#这里好像有点问题,json.load()只能读取1行,读取多行就报错:
with open(filename,‘r‘) as file2:
f1=json.load(file2)
print(f1)
print(type(f1))
结果:{‘pluno‘: ‘131001‘, ‘pluname‘: ‘egg‘, ‘price‘: ‘4.98‘, ‘qty‘: ‘100‘}
<class ‘dict‘>
原文:https://www.cnblogs.com/wssking/p/11545516.html