CSV转数组、CSV转JSON(JS+PHP双版本)
一、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双版本)相关推荐
- JS 上传CSV转JSON | JSON数据转CSV下载 | 数组转CSV
⏹转换方法来源: https://www.30secondsofcode.org/js/s/csv-to-json https://www.30secondsofcode.org/js/s/array ...
- php数组转为js json,javascript-将数组php转换为JSON时出错
我在将多维PHP数组转换为JSON时遇到了一些麻烦.我使用json_encode进行了转换,但它为null. 我正在尝试开发orgChart,数据是从CSV文件中读取的,并保存在数组中.布局和JS代码 ...
- 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 ...
- Springboot读取.csv文件并转化为JSON对象
有时候我们需要读取.csv文件并将其中的数据处理成json对象以便后续处理,在这里整理了简单的处理流程. 1. 代码实现 1)引入依赖 <dependency><groupId> ...
- c++解析csv 存入数组_使用Apache Commons CSV在Java中读写CSV
介绍 这是专门针对Java读写CSV的库的简短系列文章的第二篇,也是上一篇文章" Core Java读写CSV"的直接续篇. Apache Commons CSV 在Apache的 ...
- php 导出csv字符串,PHP CSV字符串到数组
我正在尝试将CSV字符串解析为PHP中的数组. CSV字符串具有以下属性: Delimiter: , Enclosure: " New line: \r\n 示例内容: "12 ...
- JMeter 压力測试使用函数和 CSV 文件參数化 json 数据
在 http Load Testing 中.json 数据的提交是个让人头疼的问题.本文具体介绍怎样进行 JMeter 的 json 測试提交,以及怎样将其參数化. Step 1 ht ...
- php csv to array (csv 转数组)
1. 使用类 注意: user.csv 第一行默认为数组的键, 且第一行不会被打印: (区别于下面的普通函数方法 ) 例如: name age gender zhang 23 male li 20 f ...
- 前端JS:判断list(数组)中的json对象是否重复
前端JS:判断list(数组)中的json对象是否重复 <!DOCTYPE html> <html> <head> <meta charset="u ...
最新文章
- PTA---指针错误汇总(就自己做个笔记)
- 转:求多边形的面积 算法几何
- AXURE RP EXTENSION For Chrome
- 百度云世界里的“七种武器”:PCS、BAE、Site App、ScreenX等
- 【2017-03-09】SQL Server 数据库基础、四种约束
- java构造器详解_Java中关于构造器的使用详解
- oracle正则匹配全部,sql – 返回Oracle中正则表达式的所有匹配项
- java 多态判断非空_Java 多态
- OA,ERP等源码一部分演示
- 拿不出双十一成绩单,垂直电商何以安身立命?
- 618电商大促 到底谁家赢了?大家都这么有钱的吗?
- Using the itemDoubleClick event to open nodes in a Flex Tree control
- 模拟个密保卡的效果,没用JS框架
- c语言文件修改某一行,利用C语言替换文件中某一行的方法
- zabbix安装详解
- 黑马程序员视频-微信小程序-原生框架——项目搭建
- 旧物手工机器人制作图片_自制送给小朋友的生日礼物,DIY帅气的不织布机器人...
- 前端加密js库--CryptoJs
- 图形学笔记(四)——Harris 角点检测器延申
- 淘宝口令生成器,批量生成
热门文章
- 盘点2009十佳新商业模式
- Effective C++条款05:了解C++默默编写并调用哪些函数(Know what functions C++ silently writes and calls)
- AST实战|AST入门与实战星球高频问题汇总(二)
- 织梦后台设置nofollow标签
- 聊聊rel=external nofollow和rel=noopener noreferrer
- 各大互联网公司校园招聘笔试面试题
- 替代Xshell的良心国产SSH工具软件
- Oxygen Eclipse 添加server
- error怎么开机 fan_电脑开机黑屏提示CPU Fan Error怎么解决?
- windows下运行phalcon4.1.2,php7.4.3nts版本