使用HTML 5 File API加载JSON文件

Jam*_*ron 4 html5 json fileapi

我希望用户能够在那台计算机上选择一个JSON文件,然后应该将这个JSON文件提供给客户端Javascript.

我如何使用FILE API执行此操作,最终目标是用户选择的JSON文件可用作对象,然后我可以在Javascript中使用它.这是我到目前为止:

JsonObj = null 



function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
     f = files[0];
      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
         JsonObj = e.target.result
         console.log(JsonObj);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }



document.getElementById('files').addEventListener('change', handleFileSelect, false);
Run Code Online (Sandbox Code Playgroud)

FIDDLE:http://jsfiddle.net/jamiefearon/8kUYj/

我如何将变量JsonObj转换为适当的Json对象,可以添加新的字段等.

Gra*_*ers 9

不要将数据作为"DataUrl"加载readAsDataURL,而是使用readAsText然后解析它JSON.parse()

例如

JsonObj = null 

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
     f = files[0];
      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
         JsonObj = JSON.parse(e.target.result);
         console.log(JsonObj);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsText(f);
    }

document.getElementById('files').addEventListener('change', handleFileSelect, false);
Run Code Online (Sandbox Code Playgroud)