使用 Javascript 将 CSV 数据转换为 JSON 格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27979002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert CSV data into JSON format using Javascript
提问by Pankaj
I have data in CSV format data and want to convert into JSON format using Javascript.
我有 CSV 格式的数据,想使用 Javascript 转换为 JSON 格式。
Following are csv format:
以下是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
I want to get all the books with their authors. So please how can I implement it using Javascript.
我想得到所有作者的书。那么请问我如何使用Javascript来实现它。
回答by Wesley Smith
The below should work for you.
以下应该适合你。
All credit to http://techslides.com/convert-csv-to-json-in-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("\n");
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
}
回答by mareoraft
I would check out out PapaParse. They have a file called papaparse.min.jsthat you can drop into your project if need be. PapaParse has no dependencies.
我会看看PapaParse。他们有一个名为的文件papaparse.min.js,如果需要,您可以将其放入您的项目中。PapaParse 没有依赖项。
I have used it myself and can verify it works, is convenient, and is well-documented.
我自己使用过它,可以验证它的工作原理,方便,并且有据可查。
回答by foxiris
Base on @DelightedD0D, I would add if (!lines[i]) continueso it can ignore any empty line and trailing lines.
基于@DelightedD0D,我会添加if (!lines[i]) continue以便它可以忽略任何空行和尾随行。
function csvJSON(csv) {
const lines = csv.split('\n')
const result = []
const headers = lines[0].split(',')
for (let i = 1; i < lines.length; i++) {
if (!lines[i])
continue
const obj = {}
const currentline = lines[i].split(',')
for (let j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j]
}
result.push(obj)
}
return result
}
回答by Sohel Siddiki
I think, I have a better solution, this also have one issue i.e. the values should not contain comma(,). Otherwise it is a best solution.
我想,我有一个更好的解决方案,这也有一个问题,即值不应包含逗号(,)。否则它是最好的解决方案。
// convert csv to json
csvJSON(csvText) {
let lines = [];
const linesArray = csvText.split('\n');
// for trimming and deleting extra space
linesArray.forEach((e: any) => {
const row = e.replace(/[\s]+[,]+|[,]+[\s]+/g, ',').trim();
lines.push(row);
});
// for removing empty record
lines.splice(lines.length - 1, 1);
const result = [];
const headers = lines[0].split(",");
for (let i = 1; i < lines.length; i++) {
const obj = {};
const currentline = lines[i].split(",");
for (let j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
//return result; //JavaScript object
// return JSON.stringify(result); //JSON
return result;
}
// For Reading CSV File
readCSV(event) {
const reader = new FileReader();
reader.readAsText(event.files[0]);
reader.onload = () => {
const text = reader.result;
const csvToJson = this.csvJSON(text);
console.log(csvToJson);
};
}
Thank you
谢谢
回答by mplungjan
Here is my try on your SPECIFIC example. I know it is an old question but I have used current methods
这是我对您的特定示例的尝试。我知道这是一个老问题,但我使用了当前的方法
const titlesCsv = `id;name;author
integer;string;authors:n
1;To Kill an Mockingbird;1
2;Lord of the Rings;2
3;Hamlet;3`
const authorsCsv = `id;name
integer;string
1;Harper Lee
2;JRR Tolkien
3;William Shakespeare`
const parseCsv = csv => {
let lines = csv.split("\n");
const header = lines.shift().split(";")
lines.shift(); // get rid of definitions
return lines.map(line => {
const bits = line.split(";")
let obj = {};
header.forEach((h, i) => obj[h] = bits[i]); // or use reduce here
return obj;
})
};
const titles = parseCsv(titlesCsv)
const authors = parseCsv(authorsCsv)
const books = titles.map(title => {
return {
id: title.id,
name: title.name,
author: authors.find(author => author.id === title.author).name
}
})
console.log(books)
回答by VeldMuijz
I have a similar answer like @DelightedD0D but my code can be used in conjunction with Excel directly (copy and paste from Excel into a textarea).
我有类似@DelightedD0D 的类似答案,但我的代码可以直接与 Excel 结合使用(从 Excel 复制并粘贴到文本区域)。
function csvUpload(csvText){
//Split all the text into seperate lines on new lines and carriage return feeds
var allTextLines = csvText.split(/\r\n|\n/);
//Split per line on tabs and commas
var headers = allTextLines[0].split(/\t|,/);
var lines = [];
var locations = [];
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(/\t|,/);
if (data.length == headers.length) {
var location = {"device_id":data[0], "address":data[1], "city":data[2]};
locations.push(location);
}
}
return locations;
}
This way you can use a CSV that is copied into Excel. Excel will remove the seperators like ,and others and will insert newlines etc.
这样您就可以使用复制到 Excel 中的 CSV。Excel 将删除分隔符等,,并插入换行符等。
With the my code you can pass everything into a textfield directly from Excel and then use that to create a json.
使用我的代码,您可以直接从 Excel 将所有内容传递到文本字段中,然后使用它来创建一个 json。
I have the naming of the fields static here, but you could use @DelightedD0D's code to set the headers dynamically:
我在这里为静态字段命名,但您可以使用@DelightedD0D 的代码动态设置标题:
for(var j=0;j<headers.length;j++){
obj[headers[j]] = currentline[j];
}

