How to Use Vanilla JavaScript to Fetch a JSON File, Convert the Data into an Array, and Iterate Through Each Object

Imagine having a JSON file called map.json:

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

The goal is for JavaScript to retrieve "images/mountains.png" from map.json and use it later to access the mountains.png file. I came across a helpful piece of code online that I integrated into my existing 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);

This script grants JavaScript the ability to fetch objects in map.json by simply using json_object.images.background[n]. Therefore, retrieving "images/sea.png" can be achieved by typing json_object.images.background[1]. However, this process was hindered by a warning from the console, stating:

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

Spending several hours attempting to resolve this issue through research and consulting forums and XMLHttpRequest documentation has been in vain. Despite my efforts, I have not been successful in rewriting the code correctly. It seems I may have overlooked crucial points, preventing me from finding the correct solution. Can someone provide assistance with this matter?

Answer №1

The problem in the code arises from using false for the async parameter.

A simple fix would be:

var xh_req = new XMLHttpRequest();
xh_req.open("GET", "map.json"); // Remove `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...
};

However, I recommend 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...
});

Keep in mind that any code relying on the file data must wait until the fetch is complete before running, hence placeholders are provided above for code utilizing data.

If you're working with a modern browser and loading your code as a module, consider using top-level await. This is especially convenient if you prefer letting the browser handle errors by logging them 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...

Once again, note that this approach does not include error handling.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Flexbox helps create responsive layouts with ease

Utilizing flex to centrally position my element within my layers has worked well for me, but I encountered an issue when switching to a smaller screen size. The element simply scales down in size instead of taking up the full width like it does with Bootst ...

Tips for making sure there is a delay in between each axios call in a React

Currently in the process of developing an application that needs to interact with a RestAPI by sending a specific set of inputs. However, the API has a major flaw when it comes to scalability and tends to respond with code 429 if bombarded with too many re ...

Selenium javascript troubleshooting: encountering problems with splitting strings

Hello, I am new to using selenium and encountering an issue with splitting a string. <tr> <td>storeEval</td> <td>dList = '${StaffAdminEmail}'.split('@'); </td> <td>dsplit1 </td> < ...

Integrate a Facebook Like-box within a customized jQuery modal window

I've been working on inserting the Facebook like-box code into my page and trying to display it within a jQuery modal dialog. Here's the code I'm using: <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>< ...

Integrate user interface functionality within the server component in NextJS

When considering the Server Component located in the new app/ directory within NextJS: export default async function RootLayout({ children }) { const categories = await getCategories(); // const [navigation, setNavigation] = React.useState('hidde ...

Why is the image auto-swapping script failing to display images frequently?

I have a script that is currently running to rotate between two different logos on my webpage. What I am attempting to achieve is for the page to load and then seamlessly transition from one image to the other without any blank space. Below is the code I ...

Storing an Excel file with JavaScript: A comprehensive guide

I've been struggling to save an Excel file using Javascript, but I'm facing compatibility issues with different browsers. I initially tried using BASE64 along with data URL, which worked well in Chrome and Firefox but failed in IE and Safari. ne ...

The overflow hidden property does not seem to be effective when used in conjunction with parallax

The issue arises when I attempt to use the overflow hidden property in combination with parallax scrolling. Although everything seems to be working correctly with JavaScript for parallax scrolling, setting the overflow to hidden does not contain the image ...

What is the best way to refresh my Material-UI checkboxes following updates to certain states in a React JS environment?

One of my latest projects involves an application that visualizes graphs, with all nodes originally colored blue. I included a component in the form of a checkbox that users can interact with to trigger a state change. This change dynamically alters the co ...

Can someone please help me figure out how to detect active users within my Next.js application while utilizing Supabase authentication?

I'm looking for a way to recognize users on my app in order to display green badges as visual cues. After logging into my app using Google OAuth, the session remains active even though I logged out days ago. I am unsure of the most effective algorith ...

How can I transform a large DocumentDb source into a more compact subset and format it differently if the original document does not have any field names?

An external party has provided me with a JSON string stored in Windows Azure DocumentDb: { "kind": "Data", "profileInfo": { "profileId": "12345", "accountId": "12345", }, "rows": [ [ "20140925", "762" ], [ "20 ...

What is the method for determining the level based on the provided experience points?

I've created a formula that can calculate experience based on specific levels and another formula that calculates the level based on given experience. However, there seems to be an issue with the second function as it is not returning the expected val ...

Express encounters difficulties loading JavaScript files

I'm currently working on building an express web app, but I'm encountering a problem with importing a javascript file. Within board.js, there's a line const utility = require('./utility');. However, this line is causing an error: ...

Using JQuery to Send Form Data with an Ajax POST Request

On my web Node/Express app, I have implemented a basic messaging service and am currently attempting to submit the form using Ajax with the FormData object. While the form submission works perfectly without Ajax, all the req.body values are undefined when ...

A component with angular features will not persist

I have a menu component: <nav class="mxmls-mobile-nav"> <button class="mobile-menu-btn visible-xs visible-sm " ng-click="asideVm.open = false"> <i class="ion-android-close"></i> </button> </nav> <a class ...

Get javax.json by utilizing Maven

I'm working on integrating the javax.json library into my project, so I included it in my pom.xml file as follows: <dependency> <groupId>javax.json</groupId> <artifactId>javax.json-api</artifactId> <versio ...

Adding a div element to a React component with the help of React hooks

I'm currently diving into the world of React and experimenting with creating a todo app to enhance my understanding of React concepts. Here's the scenario I'm trying to implement: The user triggers an event by clicking a button A prompt app ...

"Is there an issue with body parsing in Node.js where newline characters in the request body are not being escaped

Currently, I am in the process of building a basic reverse proxy to forward client requests to a remote server. To achieve this, I have incorporated body-parse along with express.js for Node server, enabling me to transmit the body of the request. Howeve ...

Tips for resolving issues with mysql_fetch_assoc()

Similar Question: mysql_fetch_array() error - Fixing parameter issue Whenever I execute the code below, I encounter this issue: Warning: mysql_fetch_assoc(): provided argument is not a valid MySQL result resource If anyone knows how to rectify this pro ...

Acquire Content using jQuery and Navigate page horizontally

I am trying to achieve a unique effect by capturing content x and horizontally scrolling the page while the mouse is in motion, similar to swiping on a tablet. It seems simple enough.. Capture clientX on mousedown, ScrollLeft by ClientX while moving, Di ...