使用javascript读写json文件

时间:2012-09-04 08:30:46

标签: javascript html json

  

可能重复:
  How to read and write into file using JavaScript

任何人都可以提供使用javascript读取和写入文件的示例代码吗?

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

3 个答案:

答案 0 :(得分:1)

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

但你可以使用API​​的

答案 1 :(得分:1)

这里是示例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>

答案 2 :(得分:0)

(在javascript中没有文件编程) 如果你的意思是在javascript中解析json,那么: -

  1. 您可以使用Douglas crockford JSON lib进行解析: -  JSON.parse方法 参考链接: - http://www.json.org/js.html
  2. 实施例,

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