I have a callback where i am getting the below console output when printing row.
output of row [ 'Name', 'Language' ]
output of row [ 'English', 'Fr' ]
output of row [ 'German', 'Gr' ]
output of row [ 'France', 'London' ]
I want to convert the above array into a valid json excluding the first row alone like this.
{
"English" : "Fr",
"German" : "Gr",
"France" : "London"
}
.on('record', function(row, index){
console.log("output of row", row);
var obj = {};
row.forEach(function(column, index) {
obj[row[index].trim()] = row[index].trim();
})
record.push(obj);
}
})
Additional Code
I am getting csv data which i am pushing it into a row each time. Below is the CSV Data and the array i am getting each time i read the csv data...
Language,Name
Fr,English
Gr,German
London,France
output of row [ 'Name', 'Language' ]
output of row [ 'English', 'Fr' ]
output of row [ 'German', 'Gr' ]
output of row [ 'France', 'London' ]
cvcsv()
.from.string(csv)
.transform( function(row){
row.unshift(row.pop());
return row;
})
.on('record', function(row, index){
console.log("output of row",row)
-
Please be more specific, what is the code which is generating the rows? Also, are you getting an array of rows, or consecutive calls of the callback generate new rows each time?Marco Bonelli– Marco Bonelli2015年04月15日 21:12:07 +00:00Commented Apr 15, 2015 at 21:12
-
Use stringify var myJsonString = JSON.stringify(yourArray);manuerumx– manuerumx2015年04月15日 21:12:12 +00:00Commented Apr 15, 2015 at 21:12
-
@MarcoBonelli: I am getting array on consecutive calls of the callback which is generating rows each time.Shane– Shane2015年04月15日 21:14:06 +00:00Commented Apr 15, 2015 at 21:14
3 Answers 3
Assuming that you're getting array on consecutive calls of the callback() which is generating rows each time, you can collect the rows you need, parsing each one of them into a "key": "value" pair, adding it to an object. Then, you can use the JSON.stringify() method to turn your object into a valid JSON string.
Here's a working solution according to the code you provided:
var rows = {};
cvcsv().from.string(csv).transform(function(row){
row.unshift(row.pop());
return row;
}).on('record', function(row, index){
if (index > 0) rows[row[0]] = row[1];
});
jsonRows = JSON.stringify(rows);
// Log to the console to check
console.log(jsonRows);
The result will be something like this:
{"English" : "Fr", "German" : "Gr", "France" : "London"}
3 Comments
Can you use JSON.stringify(yourArray)?
You can remove the first element from the array using shift: yourArray.shift();
1 Comment
Here's a simplified method to help translate an array of array(size 2)
function addToObject(object, row, keyIndex, valueIndex) {
object[row[keyIndex]] = row[valueIndex];
}
function test() {
var data = [[ 'Name', 'Language' ],
[ 'English', 'Fr' ],
[ 'German', 'Gr' ],
[ 'France', 'London' ]];
var obj = {};
for(var i = 1; i < data.length; i++)
// NOTE data[i] can come from any place
addToObject(obj, data[i], 0, 1);
return obj;
}