Save JSON data to text file and read it

后端 未结 2 1926
走了就别回头了
走了就别回头了 2020-12-18 17:30

Is there possible to save JSON data into local text file? So later i can use it again using by load that file and get the stored JSON data back. Actually want i really want

2条回答
  •  执笔经年
    2020-12-18 17:50

    You are asking if it is possible, you example clearly shows that it is. I think you want to know how to read the text file after you have created it. In that case, you can follow the answer in this question: Read a local text file using Javascript

    JSON is simply a formatted string that allows JavaScript to reconstruct objects, that means you simply store a string to the text file, then read it again, and convert it to object by using JSON.parse().

    Here's a working example:

    (function () {
    var textFile = null,
      makeTextFile = function (text) {
        var data = new Blob([text], {type: 'text/plain'});
    
        // If we are replacing a previously generated file we need to
        // manually revoke the object URL to avoid memory leaks.
        if (textFile !== null) {
          window.URL.revokeObjectURL(textFile);
        }
    
        textFile = window.URL.createObjectURL(data);
    
        return textFile;
      };
    
    
      var create = document.getElementById('create'),
        textbox = document.getElementById('textbox');
    
      create.addEventListener('click', function () {
        var link = document.createElement('a');
        link.setAttribute('download', 'info.txt');
        link.href = makeTextFile(textbox.value);
        document.body.appendChild(link);
    
        // wait for the link to be added to the document
        window.requestAnimationFrame(function () {
          var event = new MouseEvent('click');
          link.dispatchEvent(event);
          document.body.removeChild(link);
    		});
        
      }, false);
    })();
    
    		var fileInput = document.getElementById('files');
    		var fileDisplayArea = document.getElementById('test');
    
    		fileInput.addEventListener('change', function(e) {
    			var file = fileInput.files[0];
    			var textType = /text.*/;
    
    			if (file.type.match(textType)) {
    				var reader = new FileReader();
    
    				reader.onload = function(e) {
    					fileDisplayArea.innerText = reader.result;
    				}
    
    				reader.readAsText(file);	
    			} else {
    				fileDisplayArea.innerText = "File not supported!"
    			}
    		});
      
    
    
    
    

    Save your json string to text file, then read it. This is just a guide.

提交回复
热议问题