简体   繁体   中英

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

Let's say I have a json file named map.json:

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

What I want is for javascript to access "images/mountains.png" in map.json and use it later to retrieve the mountains.png file. I found this neat code online that I used on top of my entire code:

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

What this basically does is to allow javascript to access the objects in map.json by simply typing json_object.images.background[n] . So, if I want to get the "images/sea.png" from map.json, I just type json_object.images.background[1] and it does the job. This would've been the end if it weren't for the warning that the console kept throwing at me. It says:

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

For the next few hours, I've been attempting to solve this issue by reading forums and the XMLHttpRequest documentation, and use whatever knowledge I find to rewrite a code that does the same function as the above. Yet, I can't seem to do it. I may have missed some important points which is why I'm still not able to write the correct code. Can anyone help me with this?

The issue with that code is that it's using false for the async parameter.

The minimal change is to do this:

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...
};

But , I suggest switching to fetch instead:

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...
});

Note that in both cases, any code that wants to use the data from the file must not be run until the call to fetch it is complete, which is why I've put placeholders above for the code using data

If you're using a modern browser and loading your code as a module, you could use top-level await , which is particularly convenient if you're okay with not handling the error yourself but letting the browser just dump it to the console:

// 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...

Again, though, that's not handling errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM