Export JSON TO CSV Using AlaSQL.js [Code Snippet]
Here are the steps and the code snippet for exporting JSON to CSV using AlaSQL.js.
Join the DZone community and get the full member experience.
Join For FreeAlaSQL is a client side in-memory SQL database. It is very lightweight and fast, and it is fully functional and works in all modern browsers. Here are the steps for exporting JSON to CSV using AlaSQL.js.
- Add alasql libray (you can dowload js file or use cdn)
https://cdn.jsdelivr.net/alasql/0.3/alasql.min.js - Write query from your JSON.
Ex: (Select * INTO FILENAME.XLSX from $scope.data) - Run the file
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!--angular js-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<!--alasql library-->
<script src="https://cdn.jsdelivr.net/alasql/0.3/alasql.min.js"></script>
<script>
angular.module('app', []).controller('downloader', function($scope) {
// json data to be exported
$scope.data = [
{
id: 1,
name: "avis",
},
{
id: 2,
name: "tasis"
},
{
id: 3,
name: "ticus"
}
]
$scope.downloadReports = function() { // we can download our json data in many formats. ex: csv, excel
// var filename = "someFileName.xlsx"
var filename = "someFileName.csv"
//alasql('SELECT id as ID,name as Name INTO XLSX("' + filename + '",{headers:true}) FROM ?', [$scope.OrganizationUsersList]);
alasql('SELECT id as ID,name as Name INTO CSV("' + filename + '",{headers:true}) FROM ?', [$scope.data]);
}
});
</script>
</head>
<body ng-app="app" ng-controller="downloader">
<table border="1px">
<th>Id</th>
<th>Name</th>
<tr ng-repeat="user in data">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
</tr>
</table>
<h3> Hello , click the below button to export your data to CSV</h1>
<button class="btn btn-xs btn-white" ng-click="downloadReports()">Download Report</button>
</body>
</html>
JSON
CSV
Snippet (programming)
Published at DZone with permission of $$anonymous$$. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments