i have the following code to fetch a json file:
async function fetchData() {
const response = await fetch(URL); // wait for file to be fetched
if (!response.ok){ // error handling
console.error(response.status);
}
const data = response.json() // parse to JSON
console.log(typeof data);
console.log(data);
}
the result of this console.log(data) is:
Promise { <state>: "pending" }
<state>: "fulfilled"
<value>: Array(68) [ {…}, {…}, {…}, … ]
<prototype>: Promise.prototype { … }
I am trying to get at that array but using JSON.parse(data) does not work, giving “SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data” despite the fact that i’ve checked and there are no syntax errors.
I saw here that this was because the data was already parsed and console.log(typeof data) returns Object so i assume it is, but trying to get anything out of it with data.anything is always undefined.
JSON.stringify(data) also returns an empty string if that’s relevant.
the json is in the form:
[
{
"common_name": "Antipodes Island parakeet",
"scientific_name": "Cyanoramphus unicolor",
"other_name": [
"Antipodes Island parakeet",
"green parakeet",
"uniform parakeet"
],
"order": "Psittaciformes",
"family": "Psittaculidae",
"length": "32 cm (male), 29 cm (female)",
"weight": "130 g",
},
{
"common_name": "Yellowhead",
"scientific_name": "Mohoua ochrocephala",
"other_name": [
"Yellowhead",
"bush canary",
"mohoua"
],
"order": "Passeriformes",
"family": "Mohouidae",
"length": "15 cm",
"weight": "30 g (male); 26 g (female)",
}
]
1