简体   繁体   中英

how to convert data of type object to JSON object

hi I am using angularjs and when I print this line

 console.log(JSON.stringify($scope.data));

I am getting below data in my browser console

"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"

I want to form this data as JSON object as below

[{ "FirstName":"John1" , "LastName":"Rambo1" ...},
{ "FirstName":"John2" , "LastName":"Rambo2" ...},
{ "FirstName":"John3" , "LastName":"Rambo3" ...}] etc

please suggest me how to do this.

Your $scope.data is a string containing comma separated values, you have to first convert it to an object.

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));

Working jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM