本文目录导读:

我为您提供几种常用的Python生成JSON报表的方法:
方法1:使用内置的json模块(最常用)
import json
# 准备数据
data = {
"report_name": "销售报表",
"date": "2024-01-01",
"metrics": {
"total_sales": 100000,
"total_orders": 500,
"avg_order_value": 200
},
"top_products": [
{"name": "产品A", "sales": 30000},
{"name": "产品B", "sales": 25000},
{"name": "产品C", "sales": 20000}
]
}
# 生成JSON字符串
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# 保存到文件
with open('report.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
方法2:从CSV文件生成JSON报表
import json
import csv
def csv_to_json_report(csv_file, output_file):
"""将CSV文件转换为JSON报表"""
data = []
# 读取CSV文件
with open(csv_file, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
# 转换数值类型
for key, value in row.items():
try:
row[key] = float(value) if '.' in value else int(value)
except:
pass
data.append(row)
# 生成报表格式
report = {
"report_generated": "自动生成的CSV报表",
"total_records": len(data),
"records": data
}
# 保存JSON
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(report, f, ensure_ascii=False, indent=2)
return report
# 使用示例
csv_to_json_report('sales_data.csv', 'sales_report.json')
方法3:从数据库生成JSON报表
import json
import sqlite3
def database_to_json_report(db_file, query, output_file):
"""从数据库查询生成JSON报表"""
conn = sqlite3.connect(db_file)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
# 执行查询
cursor.execute(query)
rows = cursor.fetchall()
# 转换为字典列表
data = [dict(row) for row in rows]
# 生成报表
report = {
"query": query,
"total_results": len(data),
"generated_at": "2024-01-01T10:30:00",
"results": data
}
# 保存JSON
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(report, f, ensure_ascii=False, indent=2)
conn.close()
return report
# 使用示例
# database_to_json_report('sales.db', 'SELECT * FROM sales', 'db_report.json')
方法4:带格式化的高级JSON报表
import json
from datetime import datetime
class JSONReportGenerator:
def __init__(self, report_name):
self.report_name = report_name
self.data = {
"report_metadata": {
"name": report_name,
"generated_at": datetime.now().isoformat(),
"version": "1.0"
},
"summary": {},
"details": []
}
def add_summary(self, **kwargs):
"""添加汇总信息"""
self.data["summary"] = kwargs
def add_detail(self, item):
"""添加明细数据"""
self.data["details"].append(item)
def generate_report(self, output_file=None):
"""生成报表"""
self.data["report_metadata"]["total_items"] = len(self.data["details"])
if output_file:
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(self.data, f, ensure_ascii=False, indent=2)
print(f"报表已保存到: {output_file}")
return self.data
def pretty_print(self):
"""打印格式化的JSON"""
return json.dumps(self.data, ensure_ascii=False, indent=2)
# 使用示例
report = JSONReportGenerator("月度销售报表")
report.add_summary(
total_revenue=500000,
total_orders=1500,
average_order=333.33,
period="2024年1月"
)
report.add_detail({
"product": "笔记本电脑",
"quantity": 50,
"revenue": 250000,
"category": "电子产品"
})
report.add_detail({
"product": "手机",
"quantity": 100,
"revenue": 150000,
"category": "电子产品"
})
# 保存报表
report.generate_report("monthly_report.json")
# 打印报表
print(report.pretty_print())
方法5:处理嵌套数据的JSON报表
import json
def create_nested_report():
"""创建带嵌套结构的JSON报表"""
# 模拟复杂数据结构
report = {
"report_header": {
"title": "综合数据报表",
"department": "数据分析部",
"generated_by": "自动化脚本"
},
"sections": {
"financial": {
"revenue": {
"total": 1000000,
"by_month": {
"January": 300000,
"February": 350000,
"March": 350000
}
},
"expenses": {
"total": 600000,
"categories": {
"salary": 300000,
"equipment": 150000,
"operations": 150000
}
}
},
"operational": {
"orders": {
"total": 500,
"fulfilled": 480,
"pending": 20
},
"customers": {
"active": 200,
"new": 50,
"churned": 10
}
}
},
"charts": {
"revenue_trend": {
"type": "line",
"data_points": [
{"month": "Jan", "value": 300000},
{"month": "Feb", "value": 350000},
{"month": "Mar", "value": 350000}
]
}
}
}
# 格式化为易读的JSON
json_output = json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True)
# 保存报表
with open('complex_report.json', 'w', encoding='utf-8') as f:
f.write(json_output)
return json_output
# 生成报表
create_nested_report()
关键参数说明
indent=2:缩进2个空格,使JSON易读ensure_ascii=False:支持中文等非ASCII字符sort_keys=True:按键排序default=str:处理datetime等非序列化类型
这些方法可以根据您的具体需求选择使用,最常用的是方法1,配合适当的数据结构即可生成灵活的JSON报表。