一、CSV转JSON

function csvToArray(strData, strDelimiter) {// Check to see if the delimiter is defined. If not,then default to comma.// 检查是否定义了分隔符。如果未定义,则默认为逗号strDelimiter = (strDelimiter || ",");// Create a regular expression to parse the CSV values.// 创建一个正则表达式来解析CSV值。let objPattern = new RegExp((// Delimiters.(分隔符)"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +// Quoted fields.(引用的字段)"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +// Standard fields.(标准字段)"([^\"\\" + strDelimiter + "\\r\\n]*))"), "gi");// Create an array to hold our data. Give the array a default empty first row.// 创建一个数组来保存数据。给数组赋值一个空元素数组let arrData = [[]];// Create an array to hold our individual pattern matching groups.// 创建一个数组来保存我们的单个模式匹配组let arrMatches = null;// Keep looping over the regular expression matches until we can no longer find a match.// 正则表达式匹配上保持循环,直到我们再也找不到匹配的while (arrMatches = objPattern.exec(strData)) {console.log(arrMatches);// Get the delimiter that was found.// 获取找到的分隔符let strMatchedDelimiter = arrMatches[1];// Check to see if the given delimiter has a length// 检查给定的分隔符是否有长度// (is not the start of string) and if it matches// (不是字符串的开头)如果匹配// field delimiter. If id does not, then we know// 字段分隔符。如果身份证没有,那我们就知道了// that this delimiter is a row delimiter.// 此分隔符是行分隔符。if (strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter)) {// Since we have reached a new row of data,add an empty row to our data array.// 既然我们得到了新的一行数据,向数据数组中添加一个空行。arrData.push([]);}// Now that we have our delimiter out of the way,// 既然我们已经把分隔符弄出来了,// let's check to see which kind of value we// 让我们来看看我们需要什么样的价值观// captured (quoted or unquoted).// 捕获(引用或未引用)。let strMatchedValue;if (arrMatches[2]) {// We found a quoted value. When we capture this value, unescape any double quotes.// 我们找到一个引用值。当我们抓到这个值,取消显示任何双引号strMatchedValue = arrMatches[2].replace(new RegExp("\"\"", "g"), "\"");} else {// We found a non-quoted value.// 我们找到了一个没有引号的值。strMatchedValue = arrMatches[3];}// Now that we have our value string, let's add it to the data array.// 现在我们有了值字符串,让我们将其添加到数据数组中arrData[arrData.length - 1].push(strMatchedValue);}// 移除最后一个空数据arrData.splice(-1);// Return the parsed data.// 返回解析结果return (arrData);
}
// 转json对象
function csvToObject(csv) {var array = csvToArray(csv);var objArray = [];for (var i = 1; i < array.length; i++) {objArray[i - 1] = {};for (var k = 0; k < array[0].length && k < array[i].length; k++) {var key = array[0][k];objArray[i - 1][key] = array[i][k]}}return objArray;
}
// 转json字符串
function csvToJson(csv){return JSON.stringify(csvToObject(csv));
}
// php版本
function csvToArray($strData, $strDelimiter = null){// 检查是否定义了分隔符。如果不是,则默认为逗号。$strDelimiter = empty($strDelimiter)?",":$strDelimiter;// 创建一个正则表达式来解析CSV值。$objPattern = "/(\\".$strDelimiter."|\\r?\\n|\\r|^)". // 分隔符"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|". // 引用的字段"([^\"\\".$strDelimiter."\\r\\n]*))/i";// 标准字段// 创建一个数组来保存数据。给出数组// 默认为空的第一行$arrData = [[]];// 创建一个数组来保存我们的单个模式,匹配组$arrMatches = null;// 设置偏移量$offset = 0;while(preg_match($objPattern, $strData, $matches, PREG_OFFSET_CAPTURE, $offset)){// 获取偏移量$offset += mb_strlen($matches[0][0]);if(empty($matches[3])){continue;}// Get the delimiter that was found.// 获取找到的分隔符$strMatchedDelimiter = $matches[1][0];// Check to see if the given delimiter has a length// 检查给定的分隔符是否有长度// (is not the start of string) and if it matches// (不是字符串的开头)如果匹配// field delimiter. If id does not, then we know// 字段分隔符。如果身份证没有,那我们就知道了// that this delimiter is a row delimiter.// 此分隔符是行分隔符。if (strlen($strMatchedDelimiter) && ($strMatchedDelimiter != $strDelimiter)) {// Since we have reached a new row of data,add an empty row to our data array.// 既然我们得到了新的一行数据,向数据数组中添加一个空行。$arrData[] = [];}// Now that we have our delimiter out of the way,// 既然我们已经把分隔符弄出来了,// let's check to see which kind of value we// 让我们来看看我们需要什么样的价值观// captured (quoted or unquoted).// 捕获(引用或未引用)。$strMatchedValue = '';if ($matches[2][0]) {// We found a quoted value. When we capture this value, unescape any double quotes.// 我们找到一个引用值。当我们抓到这个值,取消显示任何双引号$strMatchedValue = preg_replace('/""/g','\"',$matches[2][0]);} else {// We found a non-quoted value.// 我们找到了一个没有引号的值。            $strMatchedValue = $matches[3][0];}// Now that we have our value string, let's add it to the data array.// 现在我们有了值字符串,让我们将其添加到数据数组中$arrData[count($arrData) - 1][] = $strMatchedValue;}// 移除最后一个空数组array_pop($arrData);return $arrData;
}

二、JSON转CSV

参考资料:
http://csv2json.com/
php正则表达式之preg_match详解

CSV转数组、CSV转JSON(JS+PHP双版本)相关推荐

  1. JS 上传CSV转JSON | JSON数据转CSV下载 | 数组转CSV

    ⏹转换方法来源: https://www.30secondsofcode.org/js/s/csv-to-json https://www.30secondsofcode.org/js/s/array ...

  2. php数组转为js json,javascript-将数组php转换为JSON时出错

    我在将多维PHP数组转换为JSON时遇到了一些麻烦.我使用json_encode进行了转换,但它为null. 我正在尝试开发orgChart,数据是从CSV文件中读取的,并保存在数组中.布局和JS代码 ...

  3. node 导出csv文件_如何使用Node.js编写CSV文件

    node 导出csv文件 A great library you can use to quickly write an array of objects to a CSV file using No ...

  4. Springboot读取.csv文件并转化为JSON对象

    有时候我们需要读取.csv文件并将其中的数据处理成json对象以便后续处理,在这里整理了简单的处理流程. 1. 代码实现 1)引入依赖 <dependency><groupId> ...

  5. c++解析csv 存入数组_使用Apache Commons CSV在Java中读写CSV

    介绍 这是专门针对Java读写CSV的库的简短系列文章的第二篇,也是上一篇文章" Core Java读写CSV"的直接续篇. Apache Commons CSV 在Apache的 ...

  6. php 导出csv字符串,PHP CSV字符串到数组

    我正在尝试将CS​​V字符串解析为PHP中的数组. CSV字符串具有以下属性: Delimiter: , Enclosure: " New line: \r\n 示例内容: "12 ...

  7. JMeter 压力測试使用函数和 CSV 文件參数化 json 数据

    在 http Load Testing 中.json 数据的提交是个让人头疼的问题.本文具体介绍怎样进行 JMeter 的 json 測试提交,以及怎样将其參数化.         Step 1 ht ...

  8. php csv to array (csv 转数组)

    1. 使用类 注意: user.csv 第一行默认为数组的键, 且第一行不会被打印: (区别于下面的普通函数方法 ) 例如: name age gender zhang 23 male li 20 f ...

  9. 前端JS:判断list(数组)中的json对象是否重复

    前端JS:判断list(数组)中的json对象是否重复 <!DOCTYPE html> <html> <head> <meta charset="u ...

最新文章

  1. python错误-Python错误解决
  2. c++构造函数以及类中变量初始化顺序
  3. 介绍 WebLogic 的一些结构和特点
  4. PythonEditor 中文图形化编程网站即将正式启用
  5. java也可以做黑客?
  6. php access allow,PHP标头不适用于Access-Control-Allow-Origin
  7. python dictionary_Python 字典(Dictionary)
  8. #控制台大学课堂点名问题_草率了!大学课堂点名新招数来袭,逃课的一个也没有躲过...
  9. 11-----的使用
  10. HDU 3729【二分匹配】
  11. html阅读器 怎么卸载,internetexplorer怎么卸载
  12. 小程序源码:微群人脉微信小程序源码下载全新社群系统优化版-多玩法安装简单
  13. 统计fasta序列条数
  14. python源码文件的后缀名_Python 源代码程序编译后的文件扩展名为_________。_学小易找答案...
  15. 五年级3月30日——4月3日课程表
  16. ChatGPT办公应用:制作PPT大纲
  17. 【短链接】——新浪、百度、搜狐等官方长链接转短链接
  18. ios自建服务器降级,iOS14降级操作步骤 iOS14怎么降级到iOS13
  19. MySql ORDER BY排序用法
  20. 解决Ubuntu18.04版本高分辨率下导致字体过小问题

热门文章

  1. android 展示大图,Android 加载超大图(原图)分析
  2. 锂离子电池被动均衡深度理解
  3. 乔布斯遗失16年采访:A级人才的自尊心,不需要呵护
  4. ILPD(印度肝病患者)分类BP算法和KNN
  5. Keras LSTM对20 Newsgroups数据集进行分类
  6. unity3dwebgl building之后没有反应_晚会是在考验明星临场反应吗?王源开场无伴奏阿云嘎差点原地跳舞...
  7. 102-gold入门
  8. JavaScript面试题整理汇总
  9. 希望成功,给点积分,才有勇气开VIP
  10. HTML 基础知识简介