当前位置: 首页 > news >正文

纯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;}// 转换为CSVcurrentCsv = 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-8const 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文件,转换数据如下图:

在这里插入图片描述

相关文章:

  • 题解:洛谷 CF2091E Interesting Ratio
  • 猫,为什么是猫?
  • Y1代码AC集
  • Python协程入门指北
  • 数据结构与算法学习笔记(Acwing提高课)----动态规划·背包模型(一)
  • 奥地利学派方法论的三个基础
  • Python TensorFlow库【深度学习框架】全面讲解与案例
  • 从MCP基础到FastMCP实战应用
  • 安全学习基础入门5集
  • 9. 深入Spring AI:刨析 ChatMemory
  • LeetCode 150题解 | 逆波兰表达式求值
  • WPF使用依赖注入框架AutoMapper
  • 第T10周:数据增强
  • 【MySQL】复合查询与内外连接
  • 日语学习-日语知识点小记-构建基础-JLPT-N4阶段(13): ておきます ています & てあります
  • OpenGL-ES 学习(15) ----纹理
  • 【Unity】 组件库分类详解
  • 【计算机视觉】语义分割:MMSegmentation:OpenMMLab开源语义分割框架实战指南
  • OpenGL-ES 学习(12) ---- VBO EBO VAO
  • 动态规划引入
  • 王受文已任中华全国工商业联合会领导班子成员
  • 陕西省通报6起违反八项规定典型问题,省卫健委原主任刘宝琴违规收受礼品礼金
  • 马上评|什么才是地方文旅宣传的正确姿势
  • 厚重与潮流交织,淮安展现“运河之都”全新城市想象
  • 举牌超200轮!中铁建7.76亿元竞得北京通州梨园宅地
  • 浙江官宣:五一假期,没电、没气、没油车辆全部免费拖离高速