2

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().age
  • let 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"]);
}
2
  • 1
    What do you think the difference is between response.json() and response.text()? Commented Sep 8, 2021 at 20:46
  • "I was told to try one of these" - by whom? None of these work. What you need is (await response.json())["age"] or (await response.json()).age or const data = await response.json(); console.log(data.age) Commented Sep 8, 2021 at 21:42

1 Answer 1

3

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);

// …
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.