Working with JSON
The Language of the Web
JSON stands for JavaScript Object Notation. It is the standard format used to send data across the internet. When your frontend (like a Next.js app) asks a backend database for user information, the database replies by sending a JSON string.
JSON vs JS Objects
JSON looks almost exactly like a JavaScript Object, with two strict rules:
- All keys MUST be wrapped in double quotes.
- JSON is fundamentally just a text string, not an active JavaScript object.
A JS Object:
const user = { name: "Himanshu", age: 25 };
The JSON equivalent:
{ "name": "Himanshu", "age": 25 }
Converting Between the Two
JavaScript provides a built-in JSON object with two crucial methods to convert data back and forth.
1. JSON.stringify() Converts a JavaScript Object into a JSON String. You use this when you want to send data to a server.
const myObj = { name: "Himanshu" };
const jsonString = JSON.stringify(myObj);
console.log(jsonString); // '{"name":"Himanshu"}'
2. JSON.parse() Converts a JSON String back into a usable JavaScript Object. You use this when you receive data from a server.
const incomingData = '{"name":"Himanshu", "status":"Online"}';
const parsedObj = JSON.parse(incomingData);
console.log(parsedObj.name); // "Himanshu"
💡 Himanshu's Tip:
JSON.parse() is very strict! If the JSON string you receive from a server is missing a double quote or has a trailing comma, it will throw a massive error and break your app. Always handle your API data carefully!
Interview Questions
- What does JSON stand for?
- Can a JSON string contain functions as values?
- What is the difference between
JSON.stringify()andJSON.parse()?