Skip to main content

Fetch API & JSON

Fetch API & JSON is a core JavaScript concept covering fetch API & JSON: JSON is a format for storing and transporting data. This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.

1. JSON (JavaScript Object Notation)

JSON is a format for storing and transporting data.

Parse (String to Object)

let text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

const obj = JSON.parse(text);

Stringify (Object to String)

const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);

2. Fetch API

The Fetch API interface allows web browser to make HTTP requests to web servers. It uses Promises.

Basic GET Request

fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.log('Request Failed', err));

Async/Await Syntax (Cleaner)

async function getTodo() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('There was a problem:', error);
}
}
Industry Standard

Before fetch, developers used XMLHttpRequest. fetch is much cleaner and is now the standard for network requests in modern browsers.

📍 Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
📍 Address
2/66 Faram Street, Rustompura
Surat395002, Gujarat, India
📞 Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition — Areas We Serve in Surat

AdajanAlthanAmroliAthwaAthwalinesBhagalBhatarBhestanCanal RoadChowkCitylightDumasGaurav PathGhod Dod RoadHaziraJahangirpuraKamrejKapodraKatargamLimbayatMagdallaMajura GateMota VarachhaNanpuraNew CitylightOlpadPalPandesaraParle PointPiplodPunaRanderRing RoadRustampuraSachinSalabatpuraSarthanaSosyo CircleUdhnaVarachhaVed RoadVesuVIP Road
📞 Call Sir💬 WhatsApp Sir