I am completely new to the world of javascript and json. My previous experience with javascript was quite minimal, about 12 years ago. So, please bear with me as I try to explain my current issue. The problem I am facing involves retrieving a second API URL from an initial API URL and using the JSON data from that file to generate an HTML page.
Let's illustrate this with an example. Imagine I have an API URL like
http://www.thiscarsite.com/API/thecars
. The structure of the JSON data retrieved from this URL might resemble something like the following:
{ "manufacturer": "Cheverolet",
"model": "Camaro",
"year": "1990",
"styles": {
"top": "convertible",
"engine"; "v8",
"address": "http://www.somesite.com/api/90ChevCamConvV8"
}
}
While I can successfully fetch the initial JSON file using the fetch/await method or a simple code snippet like this:
const startUrl = 'http://www.thiscarsite.com/API/thecars';
fetch(startUrl)
.then(response => {
return response.json();
console.log(data);
})
.catch(error => {
console.error(error);
});
The dilemma arises when trying to extract the URL from the first JSON data and then fetching the secondary JSON file. In my case, the URL in the initial JSON file changes frequently, necessitating extracting it each time before accessing the data. I've come across examples where one retrieves the URL by using
const newURL = data.styles.address;
, but how do I navigate getting this address and subsequently requesting the second JSON file?
I acknowledge that this information may be readily available through online resources. However, my lack of expertise in this field limits my ability to use the appropriate search terms effectively.
I genuinely appreciate any guidance provided to steer me in the right direction.
MY ATTEMPTS, Unsuccessful
I attempted various approaches, but integrating the second URL into my edits led to failures. For instance:
fetch('https://example.com/endpoint1')
.then(response => {
return response.json();
})
.then(data1 => {
return fetch(`https://example.com/endpoint2?data=${data1}`);
})
.then(response => {
return response.json();
})
.then(data2 => {
console.log(data2);
})
.catch(error => {
console.error(error);
});
I also experimented with utilizing two async functions, only to encounter errors such as "response already called" during execution.