Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to get object with date format from JSON file in JavaScript

I’m doing an activity with JavaScript where I must call an extern API and get the information that it contains, the JSON file structure is the next:

"dates": {
    "2020-03-22": {
        "countries": {

The problems is that when I get the information I put it in a variable named ‘info’ and to arrive to the date camp I have put the date text in another variable to concatenate with the previous object, but the problem is that returns ‘undefined’ value.

Here’s the code I made to get the information:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function callAPI() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if(this.readyState == 4 && this.status == 200){
            var info = JSON.parse(this.responseText);
            var dateApi = "2020-03-22";

            console.log(info.dates.dateApi);
        }
    }
    xmlhttp.open("GET", "https://api.covid19tracking.narrativa.com/api/2020-03-22/country/spain");
    xmlhttp.send();
}

>Solution :

Change info.dates.dateApi code to info.dates[dateApi] this should work

function callAPI() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if(this.readyState == 4 && this.status == 200){
            var info = JSON.parse(this.responseText);
            var dateApi = "2020-03-22";

            console.log(info.dates[dateApi]);
        }
    }
    xmlhttp.open("GET", "https://api.covid19tracking.narrativa.com/api/2020-03-22/country/spain");
    xmlhttp.send();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading