I’m trying to fetch a JSON text URL and parse it from text to .json format to use in this example website, but for some reason I can’t seem to get the right syntax to make it work.
I’ve tried this, then used JSON.parse() within the initialize function:
fetch('https://raw.githubusercontent.com/mdn/learning-area/main/javascript/apis/fetching-data/can-store/products.json')
.then( response => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.text();
})
.then( text => initialize(text) )
.catch( err => console.error(`Fetch problem: ${err.message}`) );
This is what I had at first but it didn’t work. Also, I tried your solution and that didn’t work either. When I tried to search up something from the JSON object array, the whole page just went blank and said “Not Found”.
@camperextraordinaire Well first of all, the code is not mine to begin with. It’s a demonstration of code from MDN that I copy and pasted from GitHub. This is the page that introduces the example website. The link to the source code is on that page as well. You can go ahead and take a look at it. I’m just taking the raw products.json file as text and trying to parse it into JSON format. The images that are being fetched are not even on my computer. I know I could just download the source files from the GitHub repository but I’m merely just testing the code out in CodePen. Just a little context to clear everything up.
@camperextraordinaire
Okay, I know it’s been awhile, but I was finally able to fix the code I was trying to run. I used some of the feedback you gave on the path of the images. All the products now display perfectly.