使用javascript读取和写入json文件

reading and writing json file using javascript

本文关键字:json 文件 javascript 读取 使用      更新时间:2023-09-26

可能重复:
如何使用JavaScript 读取和写入文件

有人能提供使用javascript读取和写入文件的示例代码吗?

目前,我正在尝试从json文件中读取输入,并将其显示在文本框中,从而为用户提供编辑数据的灵活性。编辑后的数据必须写入json文件。

这是一个示例html文件,我已经用firefox对它进行了测试,运行良好。

<!DOCTYPE html>
<html>
    <head>
        <script>        
            function handleFileSelect()
            {               
                if (window.File && window.FileReader && window.FileList && window.Blob) {
                } else {
                    alert('The File APIs are not fully supported in this browser.');
                    return;
                }   
                input = document.getElementById('fileinput');
                if (!input) {
                  alert("Um, couldn't find the fileinput element.");
               }
               else if (!input.files) {
                  alert("This browser doesn't seem to support the `files` property of file inputs.");
               }
               else if (!input.files[0]) {
                  alert("Please select a file before clicking 'Load'");               
               }
               else {
                  file = input.files[0];
                  fr = new FileReader();
                  fr.onload = receivedText;
                  fr.readAsText(file);
               }
            }
            function receivedText() {           
               //result = fr.result;
               document.getElementById('editor').appendChild(document.createTextNode(fr.result))
            }           
        </script>
    </head>
    <body>
        <input type="file" id="fileinput"/>
        <input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();'>
        <div id="editor"></div>
    </body>
</html>

在浏览器中显示的网页中运行的JavaScript无法访问客户端文件系统。

但您可以使用API的

(无javascript文件编程)如果你的意思是用javascript解析json,那么:-

  1. 您可以使用Douglas crockford JSON-lib进行解析:-JSON.parse方法请参阅链接:-http://www.json.org/js.html

示例,

var abcd= "[{"name" : "sandeep"},{"name" :"Ramesh"}]"
abcd =JSON.parse(abcd);
for (var index=0;index<abcd.length;index++){
alert(abcd[i].name);
}