Today I Learned - Rocky Kev

TIL fetchJSON

POSTED ON:

TAGS:

A snippet to fetch json data in 5 steps.
1 - add the fetch command
2 - fetch the data with async/await
3 - Run the function and catch any errors
4 - If successful, then organize the data


//1 - npm i node-fetch
const fetch = require('node-fetch');

//2 - url and fetching the data
let url =
    'http://api.steampowered.com/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/?gameid=442070&format=json';

async function fetchData(url) {
    let response = await fetch(url);
    let jsonResponse = await response.json();
    //console.log(JSON.stringify(jsonResponse));
    printData(jsonResponse);
}

//3 - run and catch any issues
fetchData(url).catch(function () {
    console.log('Could not resolve data');
});

//4 - organize the data
function printData(jsonData) {
    jsonObject = jsonData['achievementpercentages'];
    let allAchievements = jsonObject['achievements'];

    for (let achievement of allAchievements) {
        let name = achievement['name'];
        console.log(name);
    }
}

BONUS: Add the data to a class to manipulate it.

//replace the class
function printData(jsonData) {
    jsonObject = jsonData['achievementpercentages'];
    let allAchievements = jsonObject['achievements'];

    for (let achievement of allAchievements) {
        let name = achievement['name'];
        let percent = achievement['percent'];
        let newAchievement = new Achievement(name, percent);
        newAchievement.printValues();
    }
}

class Achievement {
    //what values/percents
    constructor(name, percent) {
        this.name = name;
        this.percent = percent;
    }

    //method
    printValues() {
        console.log(
            `${this.name} achievement has been completed by ${this.percent}% of people.`
        );
    }
}

Related TILs

Tagged:

TIL fetchJSON

Fetch this data

TIL fetchJSON

Fetch this data

TIL fetchJSON

Fetch this data