将 CSV 行转换为 Javascript 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28543821/
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 lines into Javascript objects
提问by GGMU
I have a simple csv file
我有一个简单的 csv 文件
people.csv:
人.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
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.
我想要做的是获取 CSV 的每一行,将其转换为 JavaScript 对象,将它们存储到数组中,然后将数组转换为 JSON 对象。
server.js:
服务器.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
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?
我的问题是,当我在 bufferString 上调用 .split('\n') 方法时,我是否真的将该 CSV 行转换为 Javascript 对象,还是有其他方法可以这样做?
回答by nanndoj
By doing this:
通过做这个:
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",...]
You have to break it again by comma using .split(',')
, then separate the headers and push it into an Javascript Object:
您必须使用 用逗号再次打破它.split(',')
,然后将标题分开并将其推送到 Javascript 对象中:
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"
}, ... }]
See this FIDDLE
看到这个小提琴
回答by dontknowathing
You could try using MVC Razor,
您可以尝试使用 MVC Razor,
<script type="text/javascript">
MyNamespace.myConfig = @Html.Raw(Json.Encode(new MyConfigObject()));
</script>
The Json.Encode will serialize the initialized object to JSON format. Then the Html.Raw will prevent it from encoding the quotes to ".
Json.Encode 会将初始化的对象序列化为 JSON 格式。然后 Html.Raw 将阻止它将引号编码为“。
Here the entire example
这里是整个例子
回答by Shaz
You can use lodash (or underscore) to help with this.
您可以使用 lodash(或下划线)来帮助解决这个问题。
var objects = _.map(arr, function(item){return item.split(',');});
var headers = objects[0];
objects.splice(0, 1); // remove the header line
populatedObject = [];
objects.forEach(function(item){
var obj = _.zipObject(headers, item);
populatedObject.push(obj);
});
The .zipObject method will match each header to each value in the items array and produce an object.
.zipObject 方法会将每个标头与 items 数组中的每个值匹配并生成一个对象。