Reputation: 63
It's been half a day now of trying to figure this out, and while some progress has been made, and a ton of useful research, I'm still a newbie so I need help.
What I need is to use the data that I'm pulling from an API to use as a JS variable. My API is giving me the following output:
{"bitcoin":{"usd":9695.66,"usd_24h_change":2.0385849528977977}}
I want to use the usd
and usd_24_change
values from that string, maybe as some JS variable for further calculations.
So far what I've managed to do was to push the string directly in HTML, so I can have a visual representation of it, however I need to pull the values from it in the backend (hope that makes sense?)
My code so far:
fetch(url)
.then(response => response.text())
.then(data => {
$('#apiPlaceholder').html(data);
});
I've honestly ran out of ideas. My only alternative would be trying to pull the values directly from the HTML string but I feel like that would be a really clunky way of doing it. I'm sure there's ways to interpret the data in the backend.
Any ideas would definitely be appreciated! :)
Upvotes: 1
Views: 193
Reputation: 522
you need to parse the response and then just save it.
fetch(url)
.then(response => response.text())
.then(data => {
const parsedData = JSON.parse(data);
const usd = parsedData.bitcoin.usd;
const usd_24h_change = parsedData.bitcoin.usd_24h_change;
});
or display it instead;
Upvotes: 0
Reputation: 100
Here's how you would go about doing that:
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data["bitcoin"]["usd"]);
console.log(data["bitcoin"]["usd_24h_change"]);
});
Upvotes: 2