Unable to Retrieve JSON data from server and storing it in a Javascript Array

I'm relatively new to delving into the realm of JavaScript and JSON, and finding it quite challenging. My current struggle involves accessing and parsing a JSON file stored on my web server into a JavaScript object. What I aim to accomplish is parsing the JSON data into an array and then manipulating that array based on various user inputs.

Here's a snippet of what the JSON data looks like:

{"log":
[{
"name":"Al",
"entries":[8,12,16,19]},
{"name":"Steve",
"entries":[11,17,22]}]}

The task at hand is to extract one of the entry arrays and store it as a JavaScript object in an array format. Here's the approach I've taken so far:

var entriesLogged;

fetch ('url to the json file').then(function(response){
  return response.json();
}).then(function(data){
  entriesLogged = data.log[0].entries;
});

Unfortunately, I've been unable to make this work effectively and persistently assign the value to the variable beyond its scope. While I was able to log the array values using console.log, manipulating the data as an object proved to be more challenging. Ideally, I would like to parse the JSON file from the server directly into a global array.

Most of the tutorials I've consulted thus far focused on logging or displaying JSON data on HTML elements, whereas my focus lies on storing these values to a global array first.

Any insights or advice on how to achieve this would be greatly appreciated.

Warm regards, Dom

Answer №1

Have you considered the timing of manipulating the entriesLogged variable after the fetch promise chain? Since the fetch operation is asynchronous, any code following the fetch chain will execute before the fetch operation is completed.

var entriesLogged;

fetch('url to the json file').then(function(response){
  return response.json();
}).then(function(data){
  entriesLogged = data.log[0].entries;
});

// The code below will run before the fetch chain completes
// Consequently, if you use entriesLogged here, it will be null

console.log(entriesLogged); // entriesLogged is null

A possible solution could involve:

.then(function(data){
  entriesLogged = data.log[0].entries;
  myFunction(entriesLogged);
});

function myFunction(myData) {
  console.log(myData); // can access entriesLogged here
}

Answer №2

The issue at hand is due to the asynchronous nature of the function call. When the call is made, a new thread is generated and JavaScript proceeds to the next line without waiting for the call to complete.

var recordsRetrieved;
fetch(something).then(function(data){recordsRetrieved = data[0]}); // this operation moves to a separate thread and takes approximately 5 milliseconds, but JavaScript does not pause for it to finish
console.log(recordsRetrieved); // this statement gets executed before the call is completed

Answer №3

When it comes to addressing variations of a specific issue, there are countless "answers" available that only explain the problem without providing a solution. (tl;dr: check out the last block of code for the solution)

The main problem lies in the fact that .fetch('URL.json') and .json() functions are asynchronous calls. This means that while the script starts processing these calls, it continues executing other commands in the script even before the async calls are completed. As a result, if you encounter a command before these asynchronous calls finish, your script won't have the necessary data.

To gain a comprehensive understanding of how asynchronous calls work in JavaScript, various resources are available. One such resource is this link: How do I return the response from an asynchronous call?

If you prefer a synchronous approach to coding like myself, a quick workaround involves creating an async main loop and utilizing the await keyword when calling async functions where you need to wait for the data to be fetched.

An example of a main loop:

(async () => {
    // insert main loop code here
})();

You can then place your code within this main loop, ensuring that you prefix every async function with the await keyword. In the given example below, ensure that your .then() functions requiring await are also declared as async. While this may seem complex initially, I will simplify it later on. Here's a revised version based on the original code:

(async () => {
    var entriesLogged;

    await fetch('url_to_the_file.json')
        .then( async function(response){
            return await response.json();
        })
        .then( function(data){
            entriesLogged = data;
        });
})();

The use of .then() is usually for post-processing tasks within async calls, but since we aim to make it synchronous in this case, we can streamline the code by breaking down the commands individually:

// Begin main loop
(async () => {
    let response = await fetch('url_to_the_file.json');
    let entriesLogged = await response.json();
})();

This should provide you with the desired outcome and hopefully prevent others from spending hours trying to resolve a seemingly simple issue.

Credit goes to the source where this solution was found: https://www.sitepoint.com/delay-sleep-pause-wait/

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

Mastering the art of sorting HTML tables with various columns using JavaScript and jQuery

When they click the button, it should alphabetize the rows in the table according to the clicked column. Is there a way to achieve this sorting functionality without using a javascript/jquery plugin or library? I prefer to develop my own code for this pa ...

How to delete vertices and their properties from a BufferGeometry using Three.js

In my Three.js project, I have a large collection of point cloud forms grouped together in a single Points object for efficient rendering using BufferGeometry in WebGLRenderer. The program allows users to interactively select a form from the point cloud, w ...

Varying outcomes in mongo due to specific field uniqueness

Recently, I've noticed issues with consistently fetching items from my mongo database. With over 4000 items stored in the database, I've encountered some unexpected behavior. Here's a glimpse at the schema: var Order = new Schema({ code: { ...

Issues with Firebase Cloud function for parsing form data

My application makes a call to a cloud function endpoint: import './App.css'; import React from 'react'; import axios from 'axios'; function App() { const [file, setFile] = React.useState(null); function fileSelected(e) ...

Invoke the parent method within the child application

I have a checkbox on the child app controller. When the user clicks it, I need to call a method from the parent controller: Parent app controller: <div ng-controller="ParentCntr as parentCntr"> <child-app></child-app> </div> C ...

Can records be searched for in a table based on the value in an object, without needing to specify a key?

In my database, I have a table named profile with various fields. An example of the data in this table is shown below: id | name (jsonb) | lots of different fields ... 1 | {en: "Some name", fr: "Un nom"} | ... 2 | {ru: "Ка ...

What is the best way to accomplish this in Next.js?

I am working on a NextJs application and I need to include a new route /cabinet with its own navigation. The challenge is that the application already has a navigation bar defined in _app.js. Is it possible to create a similar setup like _app.js for /cab ...

Is there a way for me to confirm that every character in one word also appears in another word?

I am working on a code that prompts the user to enter two words and stores them as arrays. The goal is to check if all characters in the first word already exist in the second word. If they do, the output should be "Yes"; otherwise, it should be "No". Here ...

Is the interpretation of A[i][j] impacted by the way A is defined in C programming?

Imagine having a two-dimensional array called grid defined as double grid[5][5]. It is my understanding that the following statements are accurate: Upon declaring grid, a continuous block of memory is assigned for 25 doubles, no more and no less; When an ...

automatically created button, form control named 'answer' that is not valid

Struggling with a challenge in attaching an event to a dynamically generated button. Despite conducting some research, most of the solutions suggest that this issue is typically related to a form control. However, in my scenario, the error "invalid form co ...

Custom field security rules in Firebase

My Firebase security rules are structured like this: "users": { "$uid": { // Allows write access only to the user whose uid matches the key ($uid) ".write": "auth !== null && auth.uid === $uid", // Grants read access ...

(WebApi) Unable to convert a collection of objects to Json serialization

I have encountered an issue with serializing and returning a collection of objects from a WebApi controller. Although it works fine for single object serialization, it fails when the method tries to serialize a collection of these objects. Here is an exam ...

How can you prevent JQuery AJAX from automatically redirecting after a successful form submission?

Encountered an issue with loading http://example.com/signup.ashx: The redirect from 'http://example.com/signup.ashx' to '' was blocked by the CORS policy. This is due to the absence of 'Access-Control-Allow-Origin' header on t ...

Creating a three.js shader that continuously moves the vertices of a point cloud within a sphere

My current project involves creating a points cloud with moving points that are confined within a sphere of a specified radius, X. Initially, I was able to achieve this without using shaders, but now I am experimenting with shaders to enhance the effect. ...

Verify that all dynamic radio buttons have been selected prior to submitting the form

Ensuring all dynamically generated radio buttons from the database are checked before form submission is a challenge I'm facing in my Booking Project. The scenario involves selecting food packages and subpackages, where clients need to choose their pr ...

In search of a JavaScript library that can help format strings to meet the requirements of JSON formatting

Utilizing jQuery ajax, I am transmitting updates from the client's browser to my server. However, I have noticed that there are certain characters not supported by JSON that require an additional "\" in front of each one to be properly sent. The ...

es-lint is issuing a warning about the presence of multiple modules within the node_modules directory that have names differing only in their casing

After reviewing all my import statements, I found that everything looks correct. The only unusual import I have is react-bootstrap, which I import as: import { Jumbotron, Button } from 'react-bootstrap'; I'm using the Jumbotron and Button ...

Utilizing the `this` keyword within a click handler that is passed through an intermediary function

If I initially have a click event handler in jQuery set up like this jQuery('#btn').click(_eventHandler); And handling the event as follows function _eventHandler(e){ jQuery(this).text('Clicked'); } Does the this keyword serve a ...

How can I detect the scroll action on a Select2 dropdown?

Is there a way to capture the scrolling event for an HTML element that is using Select2? I need to be able to dynamically add options to my dropdown when it scrolls. Just so you know: I am using jQuery, and the dropdown is implemented with Select2. The ...

The Angular ui-calendar introduces an innovative approach to event addition, providing users with

I need help with adding events to the angular ui calendar. Currently, I am using $scope.events.push() method to add events, but they get reset when changing the month. If anyone has experience with angular ui-calendar and event addition, please provide ...