Im creating a news app project that pulls JSON data from an API.
The API library provides a link to the "full story."
How do I change the address of window.open() when the url is essentially an array location within a JSON file?
Heres my solution thus far
HTML
<button onclick="newWindow()">Click for full story</button>
JavaScript
function newWindow(){
window.open(data.news[0].url)
}
JSON
{
"status": "ok",
"news": [
{
"id": "4e6",
"title": "Soccer team wins the World Cup"
"url": "wwww.newsnetwork.com/soccer-team-wins-the-world-cup"
...
You can use the javascript's built in function fetch, to get what your api is sending back. After that you have to make it into a object(JSON) to access it's properties.
Note: Don't forget to handle errors in case the api isn't working or you url is missing, you can do all that in the .catch
function newWindow() {
fetch("http://example.com/movies.json")
.then(response => response.json())
.then((data) => {
window.open(data.news[0].url);
})
.catch((error) => console.error("oops:",error));
}