Accessing json data in javascript

Here is a sample of my data:

[{
    "username": "username",
    "profilepic": "profilepic",
    "location": "location",
    "tweetcreatedts": "tweetcreatedts",
    "retweetcount": "retweetcount",
    "favouritecount": "favouritecount",
    "cleanselist": "cleanselist",
    "polarity": "polarity",
    "score": "score"
},
{
    "username": "Theefamilydog",
    "profilepic": "http://pbs.twimg.com/profile_images/1366973015217610755/nvJLPOAQ_normal.jpg",
    "location": "th th",
    "tweetcreatedts": "2021-03-10 23:59:51",
    "retweetcount": "0",
    "favouritecount": "1",
    "cleanselist": "@ihavedisease @moderna_tx i think both narratives are valid",
    "polarity": "0.0",
    "score": "neutral"
}]

This is a sample of my code below:

function fetchdata(){
            let theDateTime,DatesSepTime,Dates = [];

            /*
                This is to split my date and time into an array
            */
            
            fetch("./moderna_updated.json")
                .then(function(resp){
                    return resp.json(); //convert to text
                })
                .then(function(data){ //converted a json to an object
                    for(i = 1; i <= data.length; i++){
                        theDateTime = data[i].tweetcreatedts;
                        DatesSepTime = theDateTime.split(" ");
                        Dates = DatesSepTime[0];
                        console.log(Dates);
                    };
                    
                })
        };

Output at console

I only want the date from the data I have. However, the console keeps giving me that error. How do I fix this? Am I doing it correctly?

Answer

Try this

function fetchdata() {
    let theDateTime,DatesSepTime,Dates = [];
    fetch("./moderna_updated.json")
    .then((resp) => {
        return resp.json();
    })
    .then((data) => { 
        for (let obj of data) {
            let theDateTime = obj.tweetcreatedts;
            let DatesSepTime = theDateTime.split(" ");
            let Dates = DatesSepTime[0];
            console.log(Dates);
        }
    })
}

Leave a Reply

Your email address will not be published. Required fields are marked *