我希望用户能够在计算机上选择一个JSON文件,然后将这个JSON文件提供给客户端Javascript。
我将如何使用文件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对象,可以向等等添加新的字段。
发布于 2013-07-22 05:50:04
不要以"DataUrl“的形式通过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);https://stackoverflow.com/questions/14740927
复制相似问题