Reputation: 129
I was wondering if there is any way to use just a JSON file as a database to read and write straight to the file.
I'm creating a quick Mockup web app that my company wants built but they want to see a MVP to see if it will be useful before dedicating resource and time to build it properly with a real database, node etc...
For the time being just to get some basic features working like reading data from a JSON and populating dropdown lists etc...
I was wondering if it is possible to set up a JSON file to write to as well as read from?
Currently I'm reading from the JSON like you would an API:
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'pmApp.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
};
// Run loadJSON -
loadJSON(function (response) {
var json = JSON.parse(response); // Parse JSON string into object
appJS(json); //Run the App pass in json variable
});
Sorry if this is a duplicate, I've searched but couldn't find an answer.
Upvotes: 4
Views: 7497
Reputation: 1287
If you want to write to it, No. If you're just using JavaScript in the browser then you can't write to files. You will need to have some API on the backend that you can send write requests to.
If you're just making a simple mockup that you intend to use for a quick presentation and nothing else, then you could consider using localStorage or sessionStorage in the browser to temporarily store data for a quick presentation.
Upvotes: 3
Reputation: 943556
HTTP clients cannot write to arbitrary files on HTTP servers.
You need specially crafted requests (e.g. PUT) and server-side code which will recognise them and act on them.
If you are just creating a prototype, you'd probably want something like JSON Server
Upvotes: 2