具体步骤
1、保存json文件,格式示例如下
[{"id":"S001","model":"A","passed":true,"latency_ms":1999},{"id":"S002","model":"A","passed":true,"latency_ms":2000},{"id":"S003","model":"A","passed":true,"latency_ms":2001},{"id":"S004","model":"A","passed":false,"latency_ms":1999},{"id":"S005","model":"A","passed":false,"latency_ms":2000},{"id":"S006","model":"A","passed":false,"latency_ms":2001}]
2、读取文件的最小语法
importjsonfrompathlibimportPath##获取路径,__file__指当前脚本,resolve()通过解析所有符号链接,使路径变为绝对路径,parent取所在目录,with ... as ...代码块结束后自动关闭文件BASE_DIR=Path(__file__).resolve().parent input_path=BASE_DIR/"tests.json"##读取函数open().read(),encoding="utf-8":指定使用 UTF-8 字符编码,防止写入中文或特殊字符时出现乱码withinput_path.open("r",encoding="utf-8")asf:test_cases=json.load(f)print(type(test_cases),len(test_cases))
3、保存文件的最小语法
output_path=BASE_DIR/"results.json"## 写入函数open().write(),json.dump(...)把 Python 对象(这里是 report,通常是一个字典 dict 或列表 list)转换成 JSON 格式,并直接写入到文件对象 f 中,ensure_ascii=False让中文直接显示,indent=2:设置缩进为 2 个空格withoutput_path.open("w",encoding="utf-8")asf:json.dump(report,f,ensure_ascii=False,indent=2)