【问题标题】:Using HTML 5 File API to load a JSON file使用 HTML 5 File API 加载 JSON 文件
【发布时间】:2013-01-22 08:25:36
【问题描述】:

我希望用户能够在那里的计算机上选择一个 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);

FIDDLEhttp://jsfiddle.net/jamiefearon/8kUYj/

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

【问题讨论】:

  • 也许这会有所帮助。 html5rocks.com/en/tutorials/file/dndfiles
  • 我已阅读您提到的教程并更新了我的答案以向您展示我所拥有的。
  • 您的示例中有一个小的语法错误。 JsonObj = e.target.result 之后没有分号(在最里面的代码块中)

标签: javascript html json fileapi


【解决方案1】:

不要通过readAsDataURL将数据加载为“DataUrl”,而是使用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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    相关资源
    最近更新 更多