gpt4 book ai didi

javascript - 使用 HTML 5 File API 加载 JSON 文件

转载 作者:搜寻专家 更新时间:2023-10-31 08:04:02 25 4
gpt4 key购买 nike

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

FIDDLE:http://jsfiddle.net/jamiefearon/8kUYj/

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

最佳答案

不要通过 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);

关于javascript - 使用 HTML 5 File API 加载 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14740927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com