读取 JSON
jQuery.getJSON 发送一个 http 请求以从服务器检索 json。你应该只在需要从服务器(通过互联网)获取 json 时使用它,它不适合从文件中读取它。事实上,客户端 JavaScript 根本无法访问文件系统。这意味着,如果您的网络浏览器正在运行代码,则它无法读取计算机上的任何文件,除非您的用户专门使用 <input/> 元素上传文件。
因此,如果您希望用户能够上传 .json 文件,然后将其读入 javascript 对象,您可以在 html 中执行此操作:
<input type="file" id="upload">
然后在您的 javascript 中执行此操作:
document.getElementById('upload').addEventListener('change', readFile)
function readFile() {
// This will run any time a file is selected or deselected.
var files = this.files;
if (files.length === 0) {
console.log('No file is selected');
return;
}
var reader = new FileReader();
reader.onload = function(event) {
// This is where you are given access to the file as a string. Convert the string to json...
const fileText = event.target.result; // The text is stored in event.target.result
const object = JSON.parse(event.target.result); // Parse the text as json
};
reader.readAsText(files[0]);
}
如果您确实想从服务器获取 JSON,那么您可以使用 $.getJSON,除非您之后不需要解析数据。您传递给getJSON 的第一个参数绝不应该是'json',它应该是您要检索的json 的URL:
$.getJSON('https://fakewebsite.com/api/data/get', function(data) {
// here data is already json.
});
未定义的'地图'
Uncaught TypeError: Cannot read property 'map' of undefined
您在data 上调用.map,而data 未定义。 data 需要是一个数组才能使用 map。如果您正确地将data 的值设置为数组,它将开始工作。
假设您按照我上面所说的进行了操作,并且您使用输入上传了一个文件并且该文件的文本是一个 JSON 数组,您现在可以这样做:
document.getElementById('upload').addEventListener('change', readFile)
function readFile() {
// This will run any time a file is selected or deselected.
var files = this.files;
if (files.length === 0) {
console.log('No file is selected');
return;
}
var reader = new FileReader();
reader.onload = function(event) {
const fileText = event.target.result;
const array = JSON.parse(event.target.result);
array.map((data_item)=>{
//function
});
};
reader.readAsText(files[0]);
}
您的.map 函数的语法也不正确。相反,您需要像我上面所做的那样在内联函数周围使用一组括号:
data.map((data_item) => {
//function
})