有时候会遇到我们检查一个json文件或一个目录下的json文件的键值是否含有某些字段。
import os
import json
import openpyxl
# 定义函数用于检查 JSON 文件中的键值
def check_json_files(directory):
# 创建一个新的Excel工作簿
workbook = openpyxl.Workbook()
sheet = workbook.active
sheet.title = "JSON检查结果"
# 写入表头
sheet['A1'] = "文件名"
sheet['B1'] = "某一字段检查"
sheet['C1'] = "某一字段检查"
row = 2 # 从第二行开始写入数据
for filename in os.listdir(directory):
if filename.endswith(".json"):
file_path = os.path.join(directory, filename)
with open(file_path, 'r', encoding='utf-8') as file:
try:
data = json.load(file)
has_1 = "T" if "某一字段" in str(data.values()) else "F"
has_2 = "T" if "某一字段" in str(data.values()) else "F"
sheet.cell(row, 1, filename)
sheet.cell(row, 2, has_1)
sheet.cell(row, 3, has_2)
row += 1
except Exception as e:
print(f"处理文件 {file_path} 时出现错误:{e}")
# 保存工作簿到Excel文件
excel_file_path = "目录/json_check_result.xlsx"
workbook.save(excel_file_path)
print(f"检查结果已保存到 {excel_file_path}")
# 指定目录路径,检查该目录下所有 JSON 文件
directory_path = "json文件目录"
check_json_files(directory_path)