简体   繁体   English

如何读取和写入外部json文件?

[英]How to read and write to an external json file?

Anyone know how to read and write to an external JSON file using native javascript? 有人知道如何使用本机javascript读写外部JSON文件吗?

We are creating some sort of web application that allows me to create layouts using 2d drag and drop functionalities. 我们正在创建某种Web应用程序,该应用程序允许我使用2d拖放功能创建布局。 Now, the major concern that I have is that I need to insert HTML elements references on my external JSON file. 现在,我主要担心的是,我需要在外部JSON文件上插入HTML元素引用。 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. 我可以成功创建布局和所有布局,但是如果刷新页面,由于我在Web应用程序上不使用任何后端,因此设计自然会消失。 We were told that we have to use an external JSON file to accomplish this. 我们被告知必须使用外部JSON文件来完成此操作。

I do know we have to save all the html elements on the JSON file, and creating references of those is barely a problem. 我确实知道我们必须将所有html元素保存在JSON文件中,并且创建这些元素的引用几乎不是问题。 But the reading and writing from and to the external JSON file is what bothers me. 但是,从外部JSON文件读取和向外部JSON文件写入文件使我感到困扰。 If there is a way using native JS that would be great, we weren't told to use other languages or superscripts. 如果有一种使用本机JS的方法很棒,那么我们不会被告知要使用其他语言或上标。

External files cannot be written to via JavaScript. 无法通过JavaScript写入外部文件。 Though, HTML5 brings along localStorage , storage that can hold string s and integer s. 不过,HTML5带来了localStorage ,可以容纳string s和integer的存储。 We know that JSON can be serialized from a JavaScript object, and that a JavaScript object can be serialized from a JSON string. 我们知道可以从JavaScript对象序列化JSON,并且可以从JSON字符串序列化JavaScript对象。

Therefore, you could save your data to and from localStorage , serializing as you go: 因此,您可以将数据保存到localStorage或从中保存,并localStorage中进行序列化:

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'));

Use javascript FileReader for this purpose. 为此,请使用javascript FileReader Here is a sample code to read a local file and display the content in UI. 这是读取本地文件并在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. 在这里查看更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM