Transferring JSON Data into JavaScript Variables

I've been struggling to identify what's causing the issue with the code below. It seems that the values from values.json are not being loaded into the variable statesau correctly. When I use document.write(JSON.stringify(statesau)), I just get an empty object {}.

Here's the content of values.json:

{
"values": {
    "New South Wales": 8,
    "Victoria": 6,
    "Queensland": 3,
    "South Australia": 7,
    "Western Australia": 4,
    "Tasmania": 6,
    "Northern Territory": 7
}
}

Take a look at the HTML code below:

<!DOCTYPE html>
<html>
  <head>
    <title>Wave to GeoJSON</title>
    <script src="http://d3js.org/d3.v2.js" charset="utf-8"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <style type="text/css">
#states path {
  stroke: #fff;
}
    </style>
  </head>
  <body>
  <h1>Wave to GeoJSON</h1>
    <script type="text/javascript">
    var statesau={};
  $.getJSON('values.json', function(data) {
    statesau=data;
  });
  document.write(JSON.stringify(statesau));
var w = 960,
    h = 500;
var z = d3.scale.category10();
var fill = d3.scale.log()
    .domain(d3.extent(d3.values(statesau)))
    .range(["brown", "steelblue"]);
var projection = d3.geo.azimuthal()
    .origin([135, -26])
.translate([250,180])
    .scale(700);
var path = d3.geo.path()
    .projection(projection);
var svg = d3.select("body").append("svg")
    .attr("width", w)
    .attr("height", h);
var states = svg.append("g")
    .attr("id", "states");
d3.json("au-states.json", function(collection) {
  states.selectAll("path")
      .data(collection.features)
    .enter().append("path")
.attr("fill", function(d) {
         return fill(statesau[(d.properties["STATE_NAME"])]);
       })
      .attr("d", path);
});
</script>

  </body>
</html>

Answer №1

When dealing with an asynchronous function like getJSON, it is important to reorganize your code structure.

<!DOCTYPE html>
<html>
  <head>
    <title>Wave to GeoJSON</title>
    <script src="http://d3js.org/d3.v2.js" charset="utf-8"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <style type="text/css">
#states path {
  stroke: #fff;
}
    </style>
  </head>
  <body>
  <h1>Wave to GeoJSON</h1>
    <script type="text/javascript">
        var statesau={};
          $.getJSON('values.json', function(data) {
            statesau=data;
            restOfCode();
          });
          function restOfCode(){
                  document.write(JSON.stringify(statesau));
                var w = 960,
                    h = 500;
                var z = d3.scale.category10();
                var fill = d3.scale.log()
                    .domain(d3.extent(d3.values(statesau)))
                    .range(["brown", "steelblue"]);
                var projection = d3.geo.azimuthal()
                    .origin([135, -26])
                        .translate([250,180])
                    .scale(700);
                var path = d3.geo.path()
                    .projection(projection);
                var svg = d3.select("body").append("svg")
                    .attr("width", w)
                    .attr("height", h);
                var states = svg.append("g")
                    .attr("id", "states");
                d3.json("au-states.json", function(collection) {
                  states.selectAll("path")
                      .data(collection.features)
                    .enter().append("path")
                            .attr("fill", function(d) {
                         return fill(statesau[(d.properties["STATE_NAME"])]);
                       })
                      .attr("d", path);
                });
            }
        </script>

  </body>
</html>

Answer №2

The primary issue here is that, as highlighted by webdeb in the accompanying comment, the operation of $.getJSON is asynchronous. In order for document.write to work correctly, it needs to be included within the callback function like this:

$.getJSON('data.json', function(info) {
  statesData=info;
  document.write(JSON.stringify(statesData));
});

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

What is causing this promise to fail?

Exploring the use of promises in a code example has left me puzzled. Despite my efforts to understand promises, my initial attempt failed and only outputted "Promise didn't work". Upon closer inspection, I realized that the hide() function taking 400 ...

How can recursion be implemented when the items are interdependent?

I am looking to create a function that can generate a list of individuals upon whom a specific person relies. The complexity here lies in the fact that these individuals may, in turn, rely on the original person. To illustrate: const people = { ' ...

Differences between Global and Local Variables in Middleware Development

While exploring ways to manage globally used data in my research, I stumbled upon this question: See 2. Answer After integrating the suggested approach into my codebase, I encountered a problem that I would like to discuss and seek help for. I created a ...

CKEditor directive in AngularJS does not properly enforce the maxlength attribute in textarea

I am currently working on an AngularJS application with the CKEditor plugin. I have created a directive for CKEditor and everything seems to be functioning properly. However, I am facing an issue where I need to limit the character length to 50. I tried us ...

Tips for optimizing node_module file size

Currently, I'm developing 2-3 react applications and noticed that every time I run npm install, it ends up downloading numerous dependencies into the cumbersome "node-modules" folder, totaling around 250-300mb in size! This large size makes it challen ...

What exactly occurs when a "variable is declared but its value is never read" situation arises?

I encountered the same warning multiple times while implementing this particular pattern. function test() { let value: number = 0 // The warning occurs at this line: value is declared but its value is never read value = 2 return false } My curi ...

What is the best method for presenting nested JSON data in React using a key-value pair format?

This component serves as the product description section with tabs for both description and details. Selecting the description tab displays the product specifications in a tabular format. We are utilizing the Axios library to fetch JSON data from an API. I ...

Adjust the size of the Threejs canvas to fit the container dimensions

Is there a way to determine the canvas size based on its container in order to prevent scrolling? Setting the size based on the window results in the canvas being too large. ...

Vuejs: Limiting the number of items in an li tag to 5

selectPreviousSearch(index) { this.search = this.searchHistory[index]; this.showSearchHistory = false; }, <input class="form-control bg-light-blue" id="SearchText" type="text" v-model="search" @keydown.enter = 'ent ...

How can I remove the script from Response.Write?

Instead of using Response.Write to test some values in code with an alert box, I tried writing dynamic javascript directly into the page. Even after reverting the code, rebuilding, and clearing all temp data from IE, the alert still pops up. I followed a ...

Tips for updating a value within a JSONB using jsonb_set

Looking at my jsonb data, it appears like this: [{"resultId": "MIDP", "resultValue": "9.3"}, {"resultId": "RBCHistogram", "resultValue": "AAAAA"}] I am trying to update the re ...

Tips to prevent browser from freezing while creating a large number of HTML elements

I am currently utilizing Selection.js to develop a customizable grid on my website. To make this work effectively, I need a specific number of div elements to establish the selectable area. In my scenario, I generate all the divs using a for loop and then ...

Is there a way to modify a specific item within a useState Array in Reactjs?

Having a useState hook that stores data in the following structure: const [orderData, setOrderData] = useState({ demoData1: '', demoData2: '', demoData3: '', demoArrayData: [{itemName: '', itemNumber: ...

Deleting a document by ObjectID in MongoDB with Node and Express without using Mongoose: A step-by-step guide

As a newcomer to backend development, I am currently using Node/Express/MongoDB with an EJS template for the frontend. I am in the process of creating a simple todo list app to practice CRUD operations without relying on Mongoose but solely native MongoDB. ...

In JavaScript, the JSON Object only stored the final result from a loop

I am currently working on an HTML Site that features 4 inputRange sliders. My goal is to store all values from these sliders in a nested JSON Object when a user clicks on a button. However, I have encountered an issue where my JavaScript code only saves th ...

Error message in Typescript: When a class has initialized properties, a 'super' call must be the first statement in the constructor

I am currently facing some typescript errors in my project. Would you like to see a sample of the code that is causing the issue? Here is a snippet: module CoreWeb { export class Controller implements IController { public $q; ... This piece of cod ...

emailProtected pre-publish: Running `python build.py && webpack` command

i am currently using scratch-blocks through the Linux terminal I have encountered a problem which involves running the following command: python build.py && webpack [email protected] prepublish: python build.py && webpack Can anyon ...

Steps to Turn Off Automatic Loading in Jquery Ajax tabs

I've encountered an issue with auto-loading in jQuery Ajax tabs. It's causing my browser to hang up. I need to find a way to disable the auto-loading feature. Here's the scenario of what I need: On the first tab, it loads the following cate ...

One way to dynamically track if any radio buttons in a group have been selected is by utilizing JQuery

Even though there are many related resources for this question, I still need a flawless solution. I have dynamically generated five groups of radio buttons. Each group contains up to five radio buttons. I have separately validated "none checked in" and "a ...

Serve Webpack bundle on various routes - Express Way

I recently completed a web application using an Express backend and React frontend. Upon sending a request to the Express server, it undergoes a process where the URL is checked against the backend routes. If there isn't a match, the React bundle gen ...