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.
2 Answers
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);
?>
7 Comments
Jeremy Thille
I tried your snippet, it's not saving a file to the disk, it's downloading a JSON file. Not sure that's what OP wants
Aleksey Solovey
@JeremyThille the question is "save a JSON object as a .json file". My code does exactly that.
Jeremy Thille
What it doesn't do is
each time a user fills it, I want the JSON file to be appended in the project directory.Aleksey Solovey
@JeremyThille which is outside of the question's scope. For that, this can be flagged as "too broad". My answer is just an example of how a file can be saved, feel free to expand it with other specifications
Jeremy Thille
I fail to see how it's outside of the question's scope, given I have quoted the original question.
|
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?
JavaScriptonly. You gotta need some server side language aswell, likePHP.