0

I keep having an error message and the JSON file is an array, what is incorrect in the code below?

fetch("products.json")
  .then(response => response.json())
  .then(json => console.log(json));

let parsed;

try {
  parsed = JSON.parse(json);
  console.log('JSON array parsed successfully')
} catch (err) {
  console.log('ERROR..')
}

console.log(parsed)
  • `fetch()` will return a promise, it will not create a variable called `json`. Trying to read that will throw an error. You need to have your code execute *after* the promise from `fetch()` resolves. The easiest way is to add another `.then(json => { /* all the rest of the code *?})` at the end instead of having the code outside the `.then()` chain. – VLAZ Feb 18 '22 at 17:54
  • @VLAZ Thanks for your reply. I just put all the rest of the code in another .then, I have the same error message in the console: "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0" – Sugarsheet Feb 18 '22 at 17:58
  • Then that means that what you get is ***not*** JSON. It most likely means you get some HTML back. And if it's HTML, it's often some error message formatted as a page - e.g., a 404. You have to check what you actually get which will give you a hint how to proceed. If it's a 404, you're probably not accessing the correct URL. If it's a 403, then you probably need some authentication. Etc. – VLAZ Feb 18 '22 at 18:01

0 Answers0