纯html实现的json数据转csv文件

代码如下:

<!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>

1、 复制代码 保存到文本文件后缀改为.html ,谷歌浏览器打开如下图:

在这里插入图片描述

2、粘贴json数据到输入框,点击转换为CSV然后下载csv文件,转换数据如下图:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

生而为虫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值