Importing d3.JS JSON data without polluting the global scope

Here is a JSON object:

{
    "temp_data": [10,15,20]
}

I'm trying to import it:

var temp_data;
//Importing from JSON
if(true){
    d3.json("graph.json", function(error, graph) {
        if (error){
            throw error;
        }
        temp_data = graph.temp_data;
        console.log(temp_data);    //successfully logs data
    });
}

console.log("temp: " + temp_data); //Cannot retrieve data

The issue is that even though temp_data is declared as a global variable, the second log does not display the data.

Answer №1

When you pass a callback function to d3.json(), it runs asynchronously. This can lead to situations where your second console.log() executes before the "graph.json" file has been fetched, resulting in your global variable not being populated yet. To avoid this, it is important to perform any operations with the retrieved data inside the callback function itself.

Answer №2

Adding on to the information provided in the answer that was accepted: if you hold off for a brief moment, you can utilize your console.log outside of the callback:

setTimeout(function(){
    console.log("Outside of the callback: " + temp_data);
}, 1000);      

Take a look at this plunker: https://plnkr.co/edit/zTg6Y6KSVedIBT2tVCu9?p=preview

The explanation for this was already covered in the accepted answer: due to its asynchronous nature, the code after d3.json executes almost immediately, without waiting for the completion of d3.json.

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

The output from the Facebook Graph API varies depending on the script used, despite using the same non-invalid tokens

I've been working on a simple python script that can post text messages to a facebook page using requests. Initially, I was able to achieve this successfully. However, when I incorporated the same logic into a larger project of mine, a specific reque ...

Who needs a proper naming convention when things are working just fine? What's the point of conventions if they don't improve functionality?

I am a newcomer to the world of JavaScript programming and stumbled upon this example while practicing. <html> <head> <script type="text/javascript"> function changeTabIndex() { document.getElementById('1').tabIndex="3" d ...

What is the best way to handle the resolution of multiple promises as they complete?

Suppose I have three different promises each taking a varying amount of time to resolve - 1000ms, 2000ms, and 3000ms respectively. How can I simultaneously start all the promises and handle them as they get resolved? For instance: let quickPromise = new ...

Bringing in a variable from a component that is dynamically imported

I have a dynamically imported (Map) component on my page. const Map = dynamic(() => import('../components/Mapcomp'), { ssr: false, }) In addition to the component, I also need to import a variable from it. const [taskImg, setTaskImg] = useS ...

Is there a way to dynamically add <td> based on the quantity of values in a JSON object?

I have developed a program that retrieves values from JSON and I aim to display these values in a table. Currently, only the last array value is being displayed in the table even though all values are available in the console. The objective now is to dynam ...

Guide to deserializing JSON in C# with a specific type header and a variable type body

My JSON string contains a fixed type header and a variable body as shown below: [DataContract] public class ServiceResponseHeader { [DataMember] public string ErrorCode { get; set; } [DataMember] public string Message { get; set; } } [Da ...

Looking for guidance on implementing a Live Search feature using jQuery, AJAX, JSP/Servlet, MySQL, and JSON?

After conducting research, I have received varied responses regarding this topic. The table contains 2,000 records and is updated monthly with only a small number of new entries (5-10). The structure of the table is simple: id, name, data1, data2, data3 ...

Convenient Django REST API interface for integrating with external APIs

Creating a RESTful interface for a Django project involves integrating external APIs to streamline the client and frontend interactions through a single Django API. The goal is to seamlessly display data from external APIs on the browsable API pages, mimi ...

Wordpress-inspired navigation on the left

Currently, I am in search of a JavaScript library, preferably built with jQuery, that can replicate the functionality of the left menu bar in WordPress when a user is logged in. This menu features images with text, the ability to expand and collapse, a ho ...

Updating token (JWT) using interceptor in Angular 6

At first, I had a function that checked for the existence of a token and if it wasn't present, redirected the user to the login page. Now, I need to incorporate the logic of token refreshing when it expires using a refresh token. However, I'm enc ...

What is the most efficient method for removing nested keys and their corresponding curly braces in a Python dictionary?

Currently, I have a JSON file loaded as a dictionary using json.loads: dict = { "Area":[ { "id": "aira-01", "vis": [ "menu" "hamburger" ] }, { "id": "aira-02" } My goal is to remove the entire key and value pair: "id": ...

Using kotlinx.serialization to deserialize a JSON array into a sealed class

Stored as nested JSON arrays, my data is in rich text format. The plaintext of the string and annotations describing the formatting are stored in text tokens. At decode time, I aim to map the specific structure of these nested JSON arrays to a rich Kotlin ...

Display an alternative perspective based on JSON data

I am in the process of creating a straightforward project, but I find myself a bit perplexed. Within my customer controller, there are two actions: "index" and "identification". The view for each action simply displays an image. However, what I desire is t ...

Retrieve data from the table and dropdown menu by clicking a button

A script is in place that retrieves data from two columns (Members, Description) dynamically from the table upon button click. Table html Here is the JQuery code responsible for extracting values from the table: $(function() { $('#myButton') ...

Obtain data from an ajax request to be included in the form submission

Seeking assistance with my code to retrieve the selected value from ajax_details.php for submission in the form action process_details.php. Here is the code snippet: injury_details.php <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jqu ...

The hive is generating inaccurate totals for JSON objects due to miscalcul

I am encountering an issue with my external table that has a single column containing JSON objects. When I execute the following Hive query: hive> select get_json_object(data, "$.ev") from data_table limit 3; Total MapReduce jobs = 1 Launching Jo ...

Having difficulty sending string values with Axios and FormData in Vue.js

Is there a way to send both a file input and text input in a single request using Axios and FormData in Vue.js? I've come across a solution that seems straightforward: const formData = new FormData(); formData.append('file', file); formData. ...

Extract similar values from an array using JSON filtering

Is there a way to filter and display articles based on matching values from the "tags" array? For instance, how can I list only articles that contain both "foo" and "bar" keywords? [ { "articles": [ { "_id": "0", "body": "This ...

Optimizing jQuery scripts by consolidating them to reduce file size

I've created a jQuery script that performs the same task but triggers on different events, including: Page load Dropdown selection change Clicking the swap button Typing in a text field However, I had to write separate scripts for each of these eve ...

Creating a new JSON by extracting a specific branch or node from an existing JSON data

I have a Nuki Smartlock and when I make two API calls to the Nuki Bridge, I receive JSON responses. I want to apply the same logic to both responses: When requesting for current states, the JSON looks like this: [{ "deviceType": 0, "nuk ...