JSON Methods
Overview
JSON (JavaScript Object Notation) is a lightweight, language-independent data-interchange format. It is the absolute standard for sending and receiving data across the internet (e.g., from a Frontend React app to a Backend Node Server).
JavaScript provides a global JSON object with two critical methods to translate between standard JS Objects (which only exist in memory) and JSON Strings (which can be transmitted over HTTP).
Syntax
const user = { name: "Kartik", age: 22 };
// Convert a JS Object into a JSON String (Serialization)
const jsonString = JSON.stringify(user);
console.log(jsonString);
// '{"name":"Kartik","age":22}'
// Notice the double quotes around the keys!const serverResponse = '{"status":"success","userId":101}';
// Convert a JSON String back into a usable JS Object
const parsedData = JSON.parse(serverResponse);
console.log(parsedData.status); // "success"Common Pitfalls
- Trying to use single quotes around keys or values in JSON. JSON is extremely strict: ALL keys and ALL string values MUST use double quotes (
"). Also, JSON cannot store Functions,undefined, or complex objects like Dates (Dates are converted to ISO strings). - Calling
JSON.parse()on a string that isn't perfectly formatted JSON. It will throw a fatalSyntaxError. Always wrapJSON.parsein atry/catchblock when dealing with unknown data from a user or external API.
Interview Questions
JSON.stringify() an object that contains a function?The function is completely ignored and silently removed from the resulting JSON string. JSON is a text format for data, it cannot serialize executable code.
Real-World Example
Local Storage can ONLY store strings. To save a complex JS array (like a shopping cart) to the browser's hard drive, you must stringify it first.
localStorage.setItem('cart', JSON.stringify(cartArray));
const retrievedCart = JSON.parse(localStorage.getItem('cart'));Check Your Knowledge
Test your understanding of JSON Methods with these quick questions.