2013-02-06 29 views
4

我希望用戶能夠在那裏選擇計算機上的JSON文件,然後應該將此JSON文件提供給客戶端Javascript。使用HTML 5 File API加載JSON文件

我會如何使用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對象,一個可以可以添加新的領域等

+0

也許這會有所幫助。 http://www.html5rocks.com/en/tutorials/file/dndfiles/ –

+0

我已經閱讀了您提到的教程,並更新了我的答案,向您展示了我的所得。 –

+0

你的例子中有一個小的語法錯誤。 'JsonObj = e.target.result'後面沒有分號(在最內層的代碼塊中) –

回答

9

不要加載數據通過一個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);