I want to bring back the age property from the JSON created by the API but it throws this error:
SyntaxError:JSON.parse: unexpected character at line 1 column 2 of the JSON data
The console.log(await response.json()) gives me all my JSON data, but when I comment it out and put the last code line, this error occurs.
I was told to try one of these:
response.json()["age"]response.json()[age]response.json().agelet json = JSON.parse(response);console.log(json["age"]) was close, but not successful.
let table = base.getTable("test");
let view = table.getView("Donnée brut");
let age;
let query = await view.selectRecordsAsync({
sorts: [
// sort by "Prénom" in ascending order...
{
field: "Prénom"
}
]
});
// print ID & "Prénom" from each record:
for (let record of query.records) {
let name = (record.getCellValueAsString('Prénom'));
var response = await fetch('https://api.agify.io/?name=' + name);
/* console.log(await response.json()); */
let json = JSON.parse(await response.json());
console.log(json["age"]);
}
Response.prototype.json already parses the JSON.
You’re correctly awaiting this promise: await response.json().
When logging, this already logs the parsed data you need: console.log(await response.json());.
When you try JSON.parse(await response.json()), you’re coercing the object back into a string, which results in "[object Object]", which is invalid JSON, hence the error message.
Remove this JSON.parse call.
If you need the age property of the parsed JSON, use console.log((await response.json()).age);.
Remember that .json returns a Promise, not the parsed object; that’s why response.json().age and the like won’t work.
You need to await before reading the property.
Alternatively, put the parsed result in a variable first:
// …
const result = await response.json();
console.log(result.age);
// …