Skip to content

Instantly share code, notes, and snippets.

@thomasjao
Last active January 2, 2019 01:38
Show Gist options
  • Save thomasjao/bb20b1882ce9d04fc5dbd036faed45c3 to your computer and use it in GitHub Desktop.
Save thomasjao/bb20b1882ce9d04fc5dbd036faed45c3 to your computer and use it in GitHub Desktop.
A brief method of converting CSV data to JSON data format
// Suppose we import CSV files (e.g. Excel output) into our application,
// How we transfer data into JSON format
var data = data.rows;
var jsonData = [];
var titles = data.splice(0,1)[0].split(',').map( function(item) { // this line should place in the function
return item.trim(); // split raw data into "title" part and "data" part
});
// title contains first-line title
// data contains data
// merget two arrays into JSON format
function mregeToJSON( title, data ) { // use two parts as parameter
for (var i = 0, l = data.length; i < l; i++ ) {
var obj = {}; // empty JSON object to fetch a row of data
var rowData = data[i]; // final JSON object to store
for (var j = 0, len = title.length; j < len; j++ ) { // calculate items in title
obj[title[]] = deta[i].split(',')[j].trim(); // store each row data into appropriate property
}
jsonData.push( obj ); // store temperary object into final result
}
return jsonData; // return our result
}
@thomasjao
Copy link
Author

讀取 CSV 檔並轉換成 JSON 資料

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment