Reputation: 4650
Anyone know how to read and write to an external JSON file using native javascript?
We are creating some sort of web application that allows me to create layouts using 2d drag and drop functionalities. Now, the major concern that I have is that I need to insert HTML elements references on my external JSON file. I am successful in creating my layouts and all, but if I refresh my page, naturally my designs will disappear because i am using no backend on my web application. We were told that we have to use an external JSON file to accomplish this.
I do know we have to save all the html elements on the JSON file, and creating references of those is barely a problem. But the reading and writing from and to the external JSON file is what bothers me. If there is a way using native JS that would be great, we weren't told to use other languages or superscripts.
Upvotes: 0
Views: 2648
Reputation: 1530
External files cannot be written to via JavaScript. Though, HTML5 brings along localStorage
, storage that can hold string
s and integer
s. We know that JSON can be serialized from a JavaScript object, and that a JavaScript object can be serialized from a JSON string.
Therefore, you could save your data to and from localStorage
, serializing as you go:
var obj = {"audi": "r8", "color": "black"};
localStorage.setItem('myStorage', JSON.stringify(obj));
And to retrieve the object later
var obj = JSON.parse(localStorage.getItem('myStorage'));
Upvotes: 2
Reputation: 20016
Use javascript FileReader for this purpose. Here is a sample code to read a local file and display the content in UI.
<html>
<body>
<input type="file" id="fileinput" />
<div id="ReadResult"></div>
<script type="text/javascript">
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function (e) {
var contents = e.target.result;
document.getElementById("ReadResult").innerHTML = contents;
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</body>
</html>
Look here for more details.
Upvotes: 1