6

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

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

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

4

1 回答 1

11

不要将数据加载为“DataUrl” via 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);
于 2013-07-22T05:50:04.420 回答