首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用HTML5FileAPI加载JSON文件

使用HTML5FileAPI加载JSON文件
EN

Stack Overflow用户
提问于 2013-02-06 23:33:41
回答 1查看 12.5K关注 0票数 6

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

我将如何使用文件API来实现这一点,最终目标是用户选择JSON文件作为对象,然后我可以在Javascript中使用该对象。到目前为止,这就是我所拥有的:

代码语言: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);

小提琴http://jsfiddle.net/jamiefearon/8kUYj/

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

EN

回答 1

Stack Overflow用户

发布于 2013-07-22 05:50:04

不要以"DataUrl“的形式通过readAsDataURL加载数据,而是使用readAsText,然后通过JSON.parse()解析数据

例如:

代码语言: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 = 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);
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14740927

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档