JavaScript Interview Question #92

What is JSON, and how do JSON.parse() and JSON.stringify() work?

Promises, Async/Await, Fetch & Modern JavaScript Mid-Level Intermediate

Quick Interview Answer

JSON is a text data format commonly used for API communication and storage. JSON.stringify converts supported JavaScript values into JSON text, while JSON.parse converts valid JSON text into a JavaScript value.

Detailed Explanation

JSON is a text data format commonly used for API communication and storage. JSON.stringify converts supported JavaScript values into JSON text, while JSON.parse converts valid JSON text into a JavaScript value.

JSON supports objects, arrays, strings, numbers, booleans, and null, but it does not preserve every JavaScript type or behavior. Functions, undefined object properties, symbols, prototypes, and many specialized objects require different handling.

Code Example

const user = {
    id: 1,
    name: "Asif",
    active: true
};

const json = JSON.stringify(user);
const restored = JSON.parse(json);

console.log(json);
console.log(restored.name);