问题描述
我希望用户能够在那台计算机上选择一个JSON文件,然后应该将这个JSON文件提供给客户端Javascript。
I want the user to be be able to chose a JSON file on there computer, this JSON file should then be made available to the client side Javascript.
我如何使用FILE API执行此操作,最终目标是用户选择的JSON文件可用作对象,然后我可以在Javascript中使用。这是我到目前为止:
How would I do this using the FILE API, the ultimate goal is the the user selected JSON file to be available as an object which I can then play about with in Javascript. This is what I have so far:
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);
FIDDLE :
我如何转换变量JsonObj对于一个合适的Json对象,可以添加新的字段等。
How would I convert the variable JsonObj to a proper Json object, one can can add new fields to etc.
推荐答案
不要将数据作为DataUrl加载via readAsDataURL
,而是使用 readAsText
然后通过 JSON.parse()解析它
Don't load the data as a "DataUrl" via readAsDataURL
, instead use readAsText
then parse it via 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);
这篇关于使用HTML 5 File API加载JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!