Python读写json文件
json模块封装了json的读写操作,提供了以下4个函数:
dumps: 将一个Python对象编码为json对象
loads: 将一个json对象解析为Python对象
dump: 写入json文件
load: 读取json文件
下面介绍读取json文件
一 创建config.json文件如下:
[
{"symbol":"M2101","Internal":"60m","Trend":"upward","fast_window":"10","slow_window":"20"},
{"symbol":"FG2101","Internal":"60m","Trend":"downward","fast_window":"10","slow_window":"20"}
]
二 创建代码文件ReadJson.py如下:
import json with open('./config.json', 'r') as f: datas = json.load(f)#datas是字典对象 for data in datas: print("symbol", data['symbol'], " Trend ", data['Trend'])
三 运行
cmd.exe中执行python ReadJson.py命令,结果如图: