Reputation: 1
I wanted to know if there was any way to save a JSON object as a .json file in the project directory. I have a form and each time a user fills it, I want the JSON file to be appended. I'm currently using AngularJS only.
Upvotes: 0
Views: 7576
Reputation: 736
you can't save files to the disk just with javascript. maybe you really need nodejs,and use the fs module. Is it possible to write data to file using only JavaScript?
Upvotes: 0
Reputation: 4191
AngularJS is just JavaScript, so use any methods that let you save files with JS (it's better to do it with backend like PHP). One of such methods is FileSaver.js
(uses HTML5 features).
Here is a working demo:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.myJSON = {
"A": "B"
};
$scope.saveJSON = function(json) {
var jsonse = JSON.stringify(json);
var blob = new Blob([jsonse], {
type: "application/json"
});
$scope.filename = $scope.filename || "my_json";
saveAs(blob, $scope.filename + ".json");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Some JSON:
<pre>
{{myJSON | json}}
</pre>
File Name: <input type="text" ng-model="filename" /><br>
<button ng-click="saveJSON(myJSON)">Save</button>
</div>
OR you can send a request to the backend like PHP with
$http.post("createJSON.php",json).then((res)=>{...}, (err)=>{...})
And receive with:
<?php
$dataReceived = file_get_contents('php://input');
$myFile = json_decode( $dataReceived );
$path = $myFile->path; // path to store it in
$name = $myFile->name; // file name
$JSON = $myFile->json; // content
# Storing file
$file = fopen($path.$name.".json", 'w');
fwrite($file, $JSON);
fclose($file);
?>
Upvotes: 2