JavaScript将csv转为json的解决方案(1):jQuery-csv解析csv数据

CSV是Comma Separated Values的缩写,一种常用的数据存储文件格式,其中每一行是一条记录,每一条记录包含很多列,每列中的数据通常使用逗号分隔,当其中的值包含逗号时需要使用单引号或双引号包含。 其实CSV的分隔符是很灵活的,可以使用很多种。
很多js函数库都可以解析CSV文件,比较简单和简洁的是使用jQuery-csv.js。使用jQuery-csv.js解析出的CSV文件数据以data[row][item]格式存储,这是二维数组,可以根据下标获取其中的值。

准备工作,引入相关文件:

    <script src="../jquery-3.3.1.min.js"></script>
    <script type="text/javascript"
            src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/1.0.3/jquery.csv.min.js"></script>

      // read csv file and convert to json format
    var csv_file_API = 'sample.csv';
    $.ajax({
        type: 'GET',
        url: csv_file_API,
        dataType: 'text',
        success: function (data) {
            var jsonData = $.csv.toObjects(data);
            console.log(jsonData);
        }, // end: Ajax success API call
        error: function (e) {
            alert('An error occurred while processing API calls');
            console.log("API call Failed: ", e);
        },

    });

说明:
美中不足,无法实现本地访问,直接访问会出现:Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, 错误。需要http服务器支持,才能正常读取和显示。

资源链接:

  1. jQuery-csv文件:jquery-csv
  2. .csv文件模版:JavaScript将csv转为json标准的.csv文件模版
发布了105 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41290949/article/details/104274416
csv