I am performing a test, where I have to populate a form and take the options data from a given object that resides on an external file. The idea is to fetch this data in order to populate two drop down select lists, one for the chousen state and the other for its corresponding cities and the way to achieve this, should be by making use of the async / await methods and try and catch statements. Here's the json file data.js:
var stateLocs = {
"Alabama":["Birmingham","Huntsvillen"],
"California":["Los Angeles","San Diego"],
"Georgia":["Atlanta", "Augusta"],
"New York":["New York City","Buffalo","Rochester"]
};
And this is what I have done so far, since it retrieves me an error:
const getDataAsync = async () => {
try {
const res = await fetch("/js/data.js")
const data = await JSON.parse()
console.log(data.results)
data.results.map(stateLocs => console.log(stateLocs))
} catch (err) {
const errorObject = JSON.parse(err);
console.log(errorObject);
}
};
getDataAsync();
Here's the retrieved error:
Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
getDataAsync http://localhost:3000/js/scrypts.js:9
async* http://localhost:3000/js/scrypts.js:13
scrypts.js:9:30
getDataAsync http://localhost:3000/js/scrypts.js:10
AsyncFunctionNext self-hosted:690
(Asíncrono: async)
<anonymous> http://localhost:3000/js/scrypts.js:13
I believe this is due to the fact that the json is actually inside an object and I am not accessing it in the correct way...