Most APIs don't answer with sentences but with JSON, the text format they use to send data. It looks like TypeScript's arrays and objects, but it arrives as text: in the body, it is only a string.
response.json() reads that text and builds the real values it describes: a JSON […] becomes an array, and a JSON {…} becomes an object. Like response.text(), it needs await. TypeScript can't know what a server sends, so you describe the shape with an interface and add as and that type after the call. For a weather API whose body is {"city": "Paris", "temp": 18}:
interface Weather { city: string; temp: number }
const weather = await response.json() as Weather;
console.log(weather.city, weather.temp); // Paris 18
The supplier's price list is at the path /prices. Its body is a list of products, and each product is an object with an id, a name and a price, just as the starting code's interface Product describes. Your program must print:
5 products
{ id: 1, name: 'Mug', price: 5 }
Mug costs 5
Notebook costs 3
Lamp costs 14
Pen costs 1
Plant costs 6
Your task: inside main, request /prices, turn the body into an array with response.json() as a Product[] and keep it in products, print how many products there are and the first one, then loop over the array and print each product's name and price.
Assignment
Follow the Coding Tutorial to read the supplier's price list as JSON and print every product's name and price.
Hintproducts is an array of objects: products.length counts its items, products[0] is the first object, and inside the loop each product is read by key, with a dot and the key's name.
Free plan: 30 tutor messages. PRO is unlimited.
