将CSV行转换为Javascript对象 [英] convert CSV lines into Javascript objects

查看:307
本文介绍了将CSV行转换为Javascript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的csv文件

I have a simple csv file

people.csv:

people.csv:

fname, lname, uid, phone, address
John, Doe, 1, 444-555-6666, 34 dead rd
Jane, Doe, 2, 555-444-7777, 24 dead rd
Jimmy, James, 3, 111-222-3333, 60 alive way

我要执行的操作获取CSV的每一行,将其转换为JavaScript对象,将其存储到数组中,然后将数组转换为JSON对象.

What I want to do it get each line of the CSV, convert it to a JavaScript object, store them into an array, and then convert the array into a JSON object.

server.js:

server.js:

var http = require('http');
var url  = require('url');
var fs = require('fs');

var args = process.argv;
var type = args[2] || 'text';
var arr = []; 
var bufferString; 

function csvHandler(req, res){
  fs.readFile('people.csv',function (err,data) {

  if (err) {
    return console.log(err);
  }

  //Convert and store csv information into a buffer. 
  bufferString = data.toString(); 

  //Store information for each individual person in an array index. Split it by every newline in the csv file. 
  arr = bufferString.split('\n'); 
  console.log(arr); 

  for (i = 0; i < arr.length; i++) { 
    JSON.stringify(arr[i]); 
  }

  JSON.parse(arr); 
  res.send(arr);  
});
}

//More code ommitted

我的问题是,当我在bufferString上调用.split('\ n')方法时,是否真的将CSV行转换为Javascript对象?或者还有另一种方法吗?

My question is if I am actually converting that CSV lines into Javascript objects when I call the .split('\n') method on bufferString or is there another way of doing so?

推荐答案

这样做:

arr = bufferString.split('\n'); 

您将拥有一个包含所有行作为字符串的数组

you will have an array containing all rows as string

["fname, lname, uid, phone, address","John, Doe, 1, 444-555-6666, 34 dead rd",...]

您必须使用.split(',')用逗号将其再次打断,然后分离标题并将其压入Javascript对象中:

You have to break it again by comma using .split(','), then separate the headers and push it into an Javascript Object:

var jsonObj = [];
var headers = arr[0].split(',');
for(var i = 1; i < arr.length; i++) {
  var data = arr[i].split(',');
  var obj = {};
  for(var j = 0; j < data.length; j++) {
     obj[headers[j].trim()] = data[j].trim();
  }
  jsonObj.push(obj);
}
JSON.stringify(jsonObj);

然后您将拥有一个像这样的对象:

Then you will have an object like this:

[{"fname":"John",
  "lname":"Doe",
  "uid":"1",
  "phone":"444-555-6666",
  "address":"34 dead rd"
 }, ... }]

请参见 FIDDLE

这篇关于将CSV行转换为Javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆