Vanilla JS:如何检索 json 文件,将结果解析为数组,并访问每个对象

Vanilla JS: How to retrieve json file, parse the results into an array, and access each object

假设我有一个名为 map.json 的 json 文件:

{
    "images":{
        "background": ["images/mountains.png","images/sea.png"]
    }
}

我想要的是 javascript 访问 map.json 中的“images/mountains.png”并稍后使用它来检索 mountains.png 文件。我在网上找到了我在整个代码之上使用的简洁代码:

var xh_req = new XMLHttpRequest();
xh_req.open("GET", "map.json", false);
xh_req.send(null);
var json_object = JSON.parse(xh_req.responseText);

这基本上是允许 javascript 通过简单地键入 json_object.images.background[n] 来访问 map.json 中的对象。因此,如果我想从 map.json 获取“images/sea.png”,我只需键入 json_object.images.background[1] 即可。如果不是因为控制台不断向我发出警告,这将结束。它说:

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

在接下来的几个小时里,我一直在尝试通过阅读论坛和 XMLHttpRequest 文档来解决这个问题,并利用我找到的所有知识重写与上述功能相同的代码。然而,我似乎做不到。我可能错过了一些重要的点,这就是为什么我仍然无法编写正确的代码。谁能帮我解决这个问题?

该代码的问题在于它使用 false 作为 async 参数。

最小的改变是这样做:

var xh_req = new XMLHttpRequest();
xh_req.open("GET", "map.json"); // No `false`
xh_req.send(null);
xh_req.onload = () => {
    const data = JSON.parse(xh_req.responseText);
    // ...your code using `data` (it's not JSON, so I renamed it) here...
};
xh_req.onerror = error => {
    // ...show/handle error...
};

但是,我建议改用fetch

fetch("map.json")
.then(response => {
    if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
    }
    return response.json();
})
.then(data => {
    // ...your code using `data` here...
})
.catch(error => {
    // ...show/handle error...
});

请注意,在这两种情况下,任何想要使用文件中数据的代码都不能 运行,直到获取它的调用完成,这就是为什么我在上面放置了占位符使用 data

的代码

如果您使用的是现代浏览器并将代码作为模块加载,则可以使用顶级 await,如果您不介意自己不处理错误而是让浏览器只是将它转储到控制台:

// In a type="module" script on a modern browser
const response = await fetch("map.json");
if (!response.ok) {
    throw new Error(`HTTP error ${response.status}`);
}
const data = await response.json();
// ...your code using `data` here...

同样,这不是处理错误。