JSON 转 CSV 实战案例 - 5 个真实场景完整演示(2026)

1305 字
7 分钟
JSON 转 CSV 实战案例 - 5 个真实场景完整演示(2026)

💼 5 个真实场景实战案例#

本文通过 5 个真实的业务场景,演示如何使用 JSON 转 CSV 工具解决实际问题。


案例 1:电商订单导出系统#

场景描述#

公司:某电商平台
需求:每日导出 10 万 + 订单数据,供财务对账使用
挑战:

  • 数据量大(10 万条/天)
  • 嵌套结构(订单包含多个商品)
  • 格式要求严格(财务系统要求)

原始数据#

{
"orders": [
{
"orderId": "ORD20260101001",
"customer": {
"name": "张三",
"phone": "138****1234",
"address": {
"province": "北京",
"city": "北京",
"district": "朝阳"
}
},
"items": [
{
"productId": "P001",
"name": "iPhone 15",
"price": 7999,
"quantity": 1
},
{
"productId": "P002",
"name": "AirPods Pro",
"price": 1999,
"quantity": 2
}
],
"total": 11997,
"status": "completed",
"createdAt": "2026-01-01T10:30:00Z"
}
]
}

转换步骤#

步骤 1:提取订单数组

const orders = data.orders;

步骤 2:扁平化嵌套对象

const flattened = orders.map(order => ({
orderId: order.orderId,
customerName: order.customer.name,
customerPhone: order.customer.phone,
province: order.customer.address.province,
city: order.customer.address.city,
district: order.customer.address.district,
total: order.total,
status: order.status,
createdAt: order.createdAt
}));

步骤 3:处理商品数组(展开)

const expanded = [];
orders.forEach(order => {
order.items.forEach(item => {
expanded.push({
orderId: order.orderId,
customerName: order.customer.name,
productName: item.name,
price: item.price,
quantity: item.quantity,
subtotal: item.price * item.quantity,
status: order.status,
createdAt: order.createdAt
});
});
});

步骤 4:格式化日期

function formatDate(isoString) {
return new Date(isoString).toLocaleString('zh-CN', {
timeZone: 'Asia/Shanghai'
});
}

最终 CSV#

orderId,customerName,productName,price,quantity,subtotal,status,createdAt
ORD20260101001,张三,iPhone 15,7999,1,7999,completed,2026-01-01 10:30:00
ORD20260101001,张三,AirPods Pro,1999,2,3998,completed,2026-01-01 10:30:00

效果#

  • ✅ 每日自动导出
  • ✅ 财务系统直接导入
  • ✅ 对账效率提升 90%

案例 2:用户数据迁移#

场景描述#

公司:某 SaaS 企业
需求:从 MongoDB 迁移用户数据到 MySQL
数据量:50 万用户

MongoDB 数据#

[
{
"_id": "507f1f77bcf86cd799439011",
"username": "zhangsan",
"email": "zhangsan@example.com",
"profile": {
"realname": "张三",
"avatar": "https://example.com/avatar.jpg",
"bio": "个人简介"
},
"settings": {
"theme": "dark",
"language": "zh-CN"
},
"createdAt": "2024-01-01T00:00:00Z",
"lastLoginAt": "2026-01-01T12:00:00Z"
}
]

转换策略#

1. 字段映射

const mapping = {
'_id': 'user_id',
'username': 'username',
'email': 'email',
'profile.realname': 'realname',
'profile.avatar': 'avatar_url',
'profile.bio': 'bio',
'settings.theme': 'theme',
'settings.language': 'language',
'createdAt': 'created_at',
'lastLoginAt': 'last_login_at'
};

2. 数据清洗

function cleanUser(user) {
return {
...user,
// 清理空值
bio: user.profile.bio || '',
// 格式化日期
created_at: formatDate(user.createdAt),
// 转义特殊字符
realname: escapeSpecialChars(user.profile.realname)
};
}

MySQL 导入 SQL#

LOAD DATA INFILE 'users.csv'
INTO TABLE users
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(user_id, username, email, realname, avatar_url, bio, theme, language, created_at, last_login_at);

效果#

  • ✅ 50 万用户,2 小时完成迁移
  • ✅ 数据完整,零丢失
  • ✅ 无需手动处理

案例 3:日志数据分析#

场景描述#

公司:某互联网平台
需求:将 JSON 日志转为 CSV,在 Excel 中分析
日志量:日均 100 万条

日志数据#

[
{
"timestamp": 1704067200000,
"level": "INFO",
"service": "api-gateway",
"message": "User login successful",
"context": {
"userId": 12345,
"ip": "192.168.1.100",
"userAgent": "Mozilla/5.0...",
"responseTime": 45
},
"tags": ["auth", "login"]
}
]

转换处理#

1. 时间戳转换

function formatTimestamp(ts) {
return new Date(ts).toISOString()
.replace('T', ' ')
.substring(0, 19);
}

2. 扁平化 context

const flattened = logs.map(log => ({
timestamp: formatTimestamp(log.timestamp),
level: log.level,
service: log.service,
message: log.message,
userId: log.context.userId,
ip: log.context.ip,
responseTime: log.context.responseTime,
tags: log.tags.join('|')
}));

CSV 输出#

timestamp,level,service,message,userId,ip,responseTime,tags
2026-01-01 00:00:00,INFO,api-gateway,User login successful,12345,192.168.1.100,45,auth|login

Excel 分析#

数据透视表:

  • 按小时统计登录次数
  • 按服务统计错误率
  • 按地区统计用户分布

效果:

  • ✅ 快速定位问题
  • ✅ 发现性能瓶颈
  • ✅ 优化系统架构

案例 4:API 数据导出#

场景描述#

场景:从第三方 API 获取数据,导出为 CSV 供业务部门使用

API 响应#

{
"code": 200,
"data": {
"products": [
{
"id": 1,
"name": "iPhone 15",
"category": {"id": 1, "name": "手机"},
"price": {"original": 7999, "current": 6999},
"stock": {"available": 100, "reserved": 5},
"images": ["url1", "url2"],
"specs": {
"color": ["黑色", "白色", "蓝色"],
"storage": ["128G", "256G", "512G"]
}
}
],
"pagination": {
"page": 1,
"pageSize": 20,
"total": 1000
}
}
}

提取和转换#

1. 提取数据

const products = response.data.products;

2. 简化结构

const simplified = products.map(p => ({
id: p.id,
name: p.name,
category: p.category.name,
currentPrice: p.price.current,
originalPrice: p.price.original,
discount: Math.round(p.price.current / p.price.original * 10),
availableStock: p.stock.available,
mainImage: p.images[0],
colors: p.specs.color.join('/'),
storageOptions: p.specs.storage.join('/')
}));

CSV 输出#

id,name,category,currentPrice,originalPrice,discount,availableStock,mainImage,colors,storageOptions
1,iPhone 15,手机,6999,7999,9,100,url1,黑色/白色/蓝色,128G/256G/512G

使用场景#

  • ✅ 运营制作产品手册
  • ✅ 财务核算库存价值
  • ✅ 采购制定补货计划

案例 5:报表自动生成#

场景描述#

公司:某创业公司
需求:每周自动生成业务报表,发送给管理层

数据源#

{
"weeklyStats": {
"week": "2026-W01",
"revenue": {
"total": 1000000,
"growth": 15.5
},
"users": {
"new": 5000,
"active": 50000,
"churn": 200
},
"orders": {
"total": 10000,
"avgValue": 100
},
"topProducts": [
{"name": "产品 A", "sales": 1000, "revenue": 100000},
{"name": "产品 B", "sales": 800, "revenue": 80000}
]
}
}

报表 CSV#

指标,本周数值,环比增长
总收入,1000000,15.5%
新用户,5000,8.2%
活跃用户,50000,5.1%
订单数,10000,12.3%
客单价,100,3.5%

自动化流程#

// 每周一定时执行
cron.schedule('0 9 * * 1', async () => {
// 1. 获取数据
const stats = await fetchWeeklyStats();
// 2. 转换为 CSV
const csv = convertToCSV(stats);
// 3. 发送邮件
await sendEmail({
to: 'management@company.com',
subject: '周报表 - 2026-W01',
attachment: csv
});
console.log('报表已发送');
});

效果#

  • ✅ 每周一 9 点自动发送
  • ✅ 管理层及时获取数据
  • ✅ 节省人工 2 小时/周

🎯 总结与建议#

共同点#

  1. 数据扁平化:处理嵌套结构
  2. 字段映射:统一命名规范
  3. 格式转换:日期、数值格式化
  4. 数据清洗:处理空值和异常

工具选择#

小数据量(<1 万条):

中等数据量(1 万 -10 万条):

  • 脚本处理:Node.js + json2csv

大数据量(>10 万条):

  • 流式处理 + 分批

最佳实践#

  1. ✅ 先小样本测试
  2. ✅ 验证转换结果
  3. ✅ 处理边界情况
  4. ✅ 记录转换日志
  5. ✅ 建立回滚机制

相关资源#

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

最后更新于 2026-03-29,距今已过 200 天

部分内容可能已过时

公告
🎉 已升级 2.0 版本,欢迎使用。
分类
标签
站点统计
文章
197
分类
24
标签
747
总字数
334,099
运行时长
0 天
最后活动
0 天前

目录