嗨,我正在使用angularjs,当我打印这一行时
console.log(JSON.stringify($scope.data));
我的浏览器控制台中的数据低于数据
"FirstName,LastName,CII Number,Document Path\r\nJohn1,Rambo1,bulktest1,D:/MyDOJ/input_2/1000.pdf\r\nJohn2,Rambo2,bulktest2,D:/MyDOJ/input_2/1020.pdf\r\nJohn3,Rambo3,bulktest3,D:/MyDOJ/input_2/1010.pdf\r\nJohn4,Rambo4,bulktest4,D:/MyDOJ/input_2/5010.pdf\r\n"
我想将此数据形成为JSON对象,如下所示
[{ "FirstName":"John1" , "LastName":"Rambo1" ...},
{ "FirstName":"John2" , "LastName":"Rambo2" ...},
{ "FirstName":"John3" , "LastName":"Rambo3" ...}] etc
请建议我如何做到这一点。
答案 0 :(得分:0)
您的$scope.data
是一个包含逗号分隔值的字符串,您必须先将其转换为对象。
function parseCSV(csv) {
var rows = csv.split('\r\n'), //Split the CSV into rows
keys = rows.shift().split(','), //First row contains keys, so we take that out of rows
out = []; //output array
rows.forEach(function (row) {
var obj = {}; //object for our row
row.split(',').forEach(function (value, index) {
obj[keys[index]] = value; //use the key in keys and set the value
});
out.push(obj); //add object to out
});
return out;
}
var object = parseCSV($scope.data);
console.log('object', object);
console.log('json string', JSON.stringify(object));
工作jsFiddle