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

How can you integrate a variable in a JSON path in JavaScript

First of all, it’s connecting to a url and just sanitizing it all in the Front-End. The Hypixel API works so, that you take the api url for the wanted request, in this case api.hypixel.net/player?name=USERNAME&key=APIKEY, and get back a big JSON file, which my code should sanitize. So, if you’re using the Hypixel API, yeah you’re sending the API-Key through the browser, but that is a security flaw in the Hypixle API and not in my code. The sole purpose of my code is to learn more about JavaScript an show it to others.

I’m working on an API access to the Hypixel API.
This gets me a JSON, in which I want to get a specific game, that was inputted in a field an is saved in a dict.

I’m trying to integrate this like this (console.log is only for test purposes, until I give back the data to HTML):

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

let values = Array.from(document.querySelectorAll('#apiForm input'))
    .reduce((acc, input) => {
        return { ...acc, [input.id]: input.value };
    }, {})

fetch(`https://api.hypixel.net/player?name=${values.name}&key=${values.key}`)
    .then(result => result.json())
    .then(result => {
        if (result.success) {
            if (values.game in result.player.stats) {
                console.log(result.player.stats.$(values.game)) //not working
            } else {
                console.log(result.player.stats)
                console.log('Game not available or not played yet')
            }
        } else {
            console.log('Something went wrong, please check your name and API-Key or try again later')
        }
    })

How can I do this here?

The API-Form looks like this:
Form

And the JSON file looks like this:
JSON file

So when I input Bedwars for example, the path I want should result in result.player.stats.Bedwars:

>Solution :

Replace result.player.stats.$(values.game) with

result.player.stats[values.game]

Also, when putting user input into URI paths, sanitize it with encodeURIComponent or build the query string with new URLSearchParams({ ...props }).toString().

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