本文介绍了使用 Javascript 将 CSV 数据转换为 JSON 格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 CSV 格式的数据,想用 Javascript 转换成 JSON 格式.

I have data in CSV format data and want to convert into JSON format using Javascript.

以下是csv格式:

[Test.csv]
id;name;author
integer;string;authors:n
1;To Kill an Angry Bird;1

[authors.csv]
id;name
integer;string
1;Harper Lee
2;JRR Tolkien
3;William Shakespeare

我想得到所有作者的书.那么请问我如何使用Javascript来实现它.

I want to get all the books with their authors. So please how can I implement it using Javascript.

推荐答案

以下内容应该适合您.

全部归功于 http://techslides.com/convert-csv-to-json-in-javascript

//var csv is the CSV file with headers
function csvJSON(csv){

  var lines=csv.split("
");

  var result = [];

  // NOTE: If your columns contain commas in their values, you'll need
  // to deal with those before doing the next step
  // (you might convert them to &&& or something, then covert them back later)
  // jsfiddle showing the issue https://jsfiddle.net/
  var headers=lines[0].split(",");

  for(var i=1;i<lines.length;i++){

      var obj = {};
      var currentline=lines[i].split(",");

      for(var j=0;j<headers.length;j++){
          obj[headers[j]] = currentline[j];
      }

      result.push(obj);

  }

  //return result; //JavaScript object
  return JSON.stringify(result); //JSON
}

这篇关于使用 Javascript 将 CSV 数据转换为 JSON 格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:52
查看更多