Matthew Trip
Matthew Trip

Reputation: 370

How to deserialize JSON object into an interface TypeScript

const response = await fetch('https://api.codetabs.com/v1/proxy/?quest=http://hamsterland.herokuapp.com/api/users?id=330746772378877954');
const json = await response.json(); 
const user: User = JSON.parse(json);
interface User {
    id: string;
    username: string;
    avatar: string;
}

On the last line, JSON.parse(json), I receive an error that states:

Unhandled Rejection (SyntaxError): Unexpected token o in JSON at position 1

I am not sure what is causing this. The interface model matches the JSON structure.

Upvotes: 1

Views: 5522

Answers (1)

Matthew Trip
Matthew Trip

Reputation: 370

Looks like the JSON.parse(json) was unnecessary. All I had to do was

const response = await fetch('https://api.codetabs.com/v1/proxy/?quest=http://hamsterland.herokuapp.com/api/users?id=330746772378877954');
const user: User = await response.json(); 

Thank you @Taplar for the solution.

Upvotes: 4

Related Questions