Js fetch won't read external json file

I have three json files (classical.json, rock.json and ragtime.json) at a website, and an html button which allows user to select one. I want to use js fetch to populate data with the json.

But it doesn’t work! I’m new to js fetch because previously I relied on php includes. Why doesn’t this work? Why do I get An error occurred

https://communitychessclub.com/music.php?jb=ragtime

{"YT_id":'mrLFPYENwOQ', "title":"Gladiolus Rag (Scott Joplin)", "author":'Cory Hall'},
{"YT_id":'hzRWvPMzyCU', "title":"Solace (Scott Joplin)", "author":'Cory Hall'},
{"YT_id":'BweSQtoc8D0', "title":"Magnetic Rag (Scott Joplin)", "author":'Cory Hall'}

function displayData(data) { console.log(data);}

function see_more (newegg) {grab_it = newegg + '.json'; //alert (grab_it);
fetch(grab_it)
 .then(function(response) { return response.json(); })
 .then(function(data) { displayData(data); })
 .catch(function(error) { console.log('An error occurred:', error); });}

Well i’m going to go first of all with “because nothing is calling see_more on your webpage”.

If I manually invoke see_more(“ragtime”), your problem is revealed to actually be:
An error occurred: SyntaxError: Unexpected token ‘’', “{“YT_id”:'mrLFPYENw”… is not valid JSON

So your JSON file is malformed.

Let’s go look at ragtime.json…
{"YT_id":'mrLFPYENwOQ', "title":"Gladiolus Rag (Scott Joplin)", "author":'Cory Hall'},

and it’s complaint was specifically:
Unexpected token '''

So… it doesnt like the single quotes around your strings. JSON requires you to use double quotes around strings.
Note: The next thing it’s going to complain about is that your JSON is actually multiple JSON objects. You need to stuff them in an array inside a wrapping object.

{"data":[
   {object1}, 
   {object2}, 
   {object3}
]}

that way the parser can fetch and pull down an object, which you can then handle.

3 Likes