文章目录
1. 按
python中和json读写相关的主要是json模块的以下四个函数:
dumps()
: 将一个python对象编码为json对象loads()
:将一个json对象解析为python对象dump()
:将python对象写入文件load()
:从文件中读取json数据
2. dumps()
和loads()
用于Python和json对象间的相互转化
import json
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
a = json.dumps(prices) # 编码为json
print(type(a), a)
'''
<class 'str'> {"ACME": 45.23, "AAPL": 612.78, "IBM": 205.55, "HPQ": 37.2, "FB": 10.75}
'''
b = json.loads(a) # 解码为python对象
print(type(b), b)
'''
<class 'dict'> {'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.2, 'FB': 10.75}
'''
3. dump()
与load()
用于读写json文件
3.1. dump()
用于写入数据至json文件
import json
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
with open('price.json', 'w') as f:
json.dump(prices, f)
f.close()
此时在当前目录下生成prices.json
文件。
3.2. 读取json文件
import json
with open('price.json', 'r') as f:
a = json.load(f) # 此时a是一个字典对象
print(a['ACME'])
f.close()
'''
Out[47]: 45.23
'''
4. 实际应用
import json
rawData = [(1, 7975), (2, 211), (3, 10), (4, 7), (5, 2), (6, 3), (7, 1), (8, 1), (9, 0)]
def handleRawData(RawData):
data = []
dataAxis = []
for i in RawData:
data.append(i[1])
dataAxis.append((i[0]))
dic = {
"data": data,
"dataAxis": dataAxis
}
return dic
def writeDataToJsonFile(filePath, data):
with open(filePath, 'w') as f:
json.dump(data, f)
f.close()
writeDataToJsonFile(r'D:\0\G\Graph\DataAnalysis\static\data.json', handleRawData(rawData))