代码如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON转CSV转换器</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.container {
display: flex;
flex-direction: column;
gap: 15px;
}
textarea {
width: 100%;
height: 200px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
resize: vertical;
}
button {
padding: 10px 15px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #45a049;
}
#result {
margin-top: 20px;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
min-height: 100px;
white-space: pre-wrap;
background-color: #f9f9f9;
}
.error {
color: red;
margin-top: 10px;
}
.button-group {
display: flex;
gap: 10px;
}
#downloadBtn {
background-color: #2196F3;
}
#downloadBtn:hover {
background-color: #0b7dda;
}
</style>
</head>
<body>
<h1>JSON数组转换为CSV</h1>
<div class="container">
<label for="jsonInput">请输入JSON数组:</label>
<textarea id="jsonInput" placeholder='例如:[{"name":"张三","age":25,"city":"北京"},{"name":"李四","age":30,"city":"上海"}]'>[{"name":"张三","age":25,"city":"北京"},{"name":"李四","age":30,"city":"上海"}]</textarea>
<div class="button-group">
<button id="convertBtn">转换为CSV</button>
<button id="downloadBtn" disabled>下载CSV文件</button>
</div>
<div id="error" class="error"></div>
<label for="result">CSV结果:</label>
<div id="result"></div>
</div>
<script>
let currentCsv = ''; // 存储当前转换的CSV内容
document.getElementById('convertBtn').addEventListener('click', function() {
const jsonInput = document.getElementById('jsonInput').value.trim();
const resultDiv = document.getElementById('result');
const errorDiv = document.getElementById('error');
const downloadBtn = document.getElementById('downloadBtn');
// 清空之前的错误和结果
errorDiv.textContent = '';
resultDiv.textContent = '';
downloadBtn.disabled = true;
if (!jsonInput) {
errorDiv.textContent = '请输入JSON内容';
return;
}
try {
// 解析JSON输入
const jsonArray = JSON.parse(jsonInput);
if (!Array.isArray(jsonArray)) {
errorDiv.textContent = '输入的不是JSON数组';
return;
}
if (jsonArray.length === 0) {
errorDiv.textContent = 'JSON数组为空';
return;
}
// 转换为CSV
currentCsv = convertJsonToCsv(jsonArray);
// 显示结果
resultDiv.textContent = currentCsv;
// 启用下载按钮
downloadBtn.disabled = false;
} catch (e) {
errorDiv.textContent = 'JSON解析错误: ' + e.message;
}
});
// 下载按钮点击事件
document.getElementById('downloadBtn').addEventListener('click', function() {
if (!currentCsv) {
document.getElementById('error').textContent = '没有可下载的CSV内容';
return;
}
// 添加UTF-8 BOM头,解决Excel中文乱码问题
const bom = '\uFEFF';
const csvWithBom = bom + currentCsv;
// 创建一个Blob对象,指定编码为UTF-8
const blob = new Blob([csvWithBom], { type: 'text/csv;charset=utf-8;' });
// 创建一个下载链接
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
// 设置下载属性
link.setAttribute('href', url);
link.setAttribute('download', 'data.csv');
link.style.visibility = 'hidden';
// 添加到DOM并触发点击
document.body.appendChild(link);
link.click();
// 清理
document.body.removeChild(link);
URL.revokeObjectURL(url);
});
/**
* 将JSON数组转换为CSV字符串
* [url=home.php?mod=space&uid=952169]@Param[/url] {Array} jsonArray - JSON对象数组
* @returns {string} CSV格式的字符串
*/
function convertJsonToCsv(jsonArray) {
// 收集所有可能的列标题
const headers = new Set();
jsonArray.forEach(item => {
Object.keys(item).forEach(key => {
headers.add(key);
});
});
// 将Set转换为数组
const headerArray = Array.from(headers);
// 构建CSV内容
let csv = '';
// 添加标题行
csv += headerArray.join(',') + '\n';
// 添加数据行
jsonArray.forEach(item => {
const row = headerArray.map(header => {
// 处理值中的逗号和换行符
let value = item[header] !== undefined ? item[header] : '';
if (typeof value === 'string') {
// 如果值包含逗号、换行符或双引号,需要用双引号包裹
if (value.includes(',') || value.includes('\n') || value.includes('"')) {
// 转义双引号
value = value.replace(/"/g, '""');
value = `"${value}"`;
}
}
return value;
});
csv += row.join(',') + '\n';
});
return csv;
}
</script>
</body>
</html>