Ray Stevens
Ray Stevens

Reputation: 21

Parsing a JSON object with Javascript, just won't work

I'm using this code to get a JSON file stored in the same folder.

var schedtotal = 0;
var requestURL11 = 'schedtotal.json';
var request11 = new XMLHttpRequest();
request11.open('GET', requestURL11);
request11.responseType = 'json';
request11.send();
request11.onload = function() {
window.superHeroes11 = request11.response;
populateHeader11(superHeroes11);
}


function populateHeader11(jsonObj) {
window.schedtotal = jsonObj.total;
console.log("populateHeader function has activated");
console.log(jsonObj);
}

The file looks like this:

{"total": 3}

It's valid JSON. I'm trying to extract the value of total using the same exact method that I've used successfully for all the other JSON parsings in the rest of the file (which I have not included here).

When populateHeader11 is called, it doesn't change schedtotal to equal total. It remains at its original setting of 0. The console log returns from the function as having activated and also returns the JSON file so I know it can access it at least.

I've tried changing .jsonObj.total to .jsonObj['total'] and it didn't change anything.

Previous times I've screwed around with this, it has sometimes returned an error saying it can't get 'total' from null. Now it just doesn't return anything in its current state. What is going on?

Upvotes: 0

Views: 64

Answers (1)

Matt
Matt

Reputation: 3760

You need to parse the JSON string into an object before you try and access the total field.

var jsonString = "{\"total\": 3}";
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.total);

Upvotes: 2

Related Questions