JavaScript JSON
JavaScript JSON Interview with follow-up questions
1. What is JSON in JavaScript and why is it used?
JSON (JavaScript Object Notation) is a lightweight, text-based format for storing and exchanging structured data. Its syntax is derived from JavaScript object literals, but it's language-independent — virtually every platform can parse it, which is why it's the default format for web APIs (largely replacing XML).
It's used because it's human-readable, compact, and maps cleanly to objects/arrays. In the browser, fetch responses are typically JSON: you serialize with JSON.stringify() and parse with JSON.parse().
const user = { name: "Ada", roles: ["admin"] };
const text = JSON.stringify(user); // '{"name":"Ada","roles":["admin"]}'
const back = JSON.parse(text); // back to an object
Follow-ups interviewers expect — JSON ≠ a JavaScript object:
- JSON is a string format; keys must be double-quoted, no trailing commas, no comments, no functions.
- Only these value types are allowed: string, number, boolean,
null, array, object. There's noDate,undefined,Map,BigInt, or circular references —Dates become ISO strings,undefined/functions are dropped, and cycles throw. Restore types with aJSON.parsereviver function.
Follow-up 1
How is JSON different from XML?
JSON and XML are both used for data interchange, but they have some key differences:
- Syntax: JSON uses a simple and compact syntax, while XML uses a more verbose and complex syntax.
- Data Types: JSON supports a limited set of data types, including strings, numbers, booleans, arrays, and objects. XML can represent a wider range of data types.
- Readability: JSON is generally easier to read and write for humans, while XML is more verbose and can be harder to read.
- Parsing: JSON can be parsed more quickly and efficiently than XML, as it requires less code and processing.
Overall, JSON is often preferred for web applications due to its simplicity and ease of use.
Follow-up 2
Can you give an example of JSON data?
Sure! Here's an example of JSON data:
{
"name": "John Doe",
"age": 30,
"city": "New York"
}
In this example, we have an object with three properties: "name", "age", and "city". The values can be strings, numbers, booleans, arrays, or even nested objects.
Follow-up 3
How can we parse JSON data in JavaScript?
In JavaScript, you can parse JSON data using the JSON.parse() method. This method takes a JSON string as input and returns a JavaScript object.
Here's an example:
const jsonString = '{"name": "John Doe", "age": 30, "city": "New York"}';
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject);
The JSON.parse() method converts the JSON string into a JavaScript object, which can then be accessed and manipulated like any other JavaScript object.
Follow-up 4
What are the methods provided by JavaScript to work with JSON data?
JavaScript provides two main methods to work with JSON data:
JSON.stringify(): This method converts a JavaScript object into a JSON string. It takes an object as input and returns a JSON string representation of the object.
Here's an example:
const jsonObject = {"name": "John Doe", "age": 30, "city": "New York"};
const jsonString = JSON.stringify(jsonObject);
console.log(jsonString);
The JSON.stringify() method converts the JavaScript object into a JSON string, which can then be transmitted or stored.
JSON.parse(): This method converts a JSON string into a JavaScript object. It takes a JSON string as input and returns a JavaScript object.
Here's an example:
const jsonString = '{"name": "John Doe", "age": 30, "city": "New York"}';
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject);
The JSON.parse() method converts the JSON string into a JavaScript object, which can then be accessed and manipulated like any other JavaScript object.
2. How can you convert a JavaScript object into a JSON string?
Use JSON.stringify() to serialize a JavaScript value into a JSON string:
const user = { name: "Ada", age: 36 };
JSON.stringify(user); // '{"name":"Ada","age":36}'
// 3rd arg = indentation for pretty-printing
JSON.stringify(user, null, 2);
Follow-ups interviewers like to push on:
- What gets dropped: properties whose value is
undefined, a function, or aSymbolare omitted in objects (and becomenullinside arrays).BigIntthrows aTypeError. - Type loss:
Dateobjects are converted to ISO strings, andMap/Setserialize to{}— they don't round-trip. - Circular references throw a
TypeError. toJSON: if an object defines atoJSON()method,stringifyuses its return value (that's howDateworks).- The replacer (2nd arg) lets you filter or transform — either an allow-list array of keys or a function:
JSON.stringify(user, ["name"]); // '{"name":"Ada"}'
Follow-up 1
What is the syntax for this conversion?
The syntax for converting a JavaScript object into a JSON string using JSON.stringify() method is as follows:
const jsonString = JSON.stringify(object);
Follow-up 2
What is the use of the JSON.stringify() method?
The JSON.stringify() method is used to convert a JavaScript object into a JSON string. It serializes the object by converting its properties into a string representation that can be easily transmitted or stored. This method is commonly used when sending data to a server or when storing data in a file.
Follow-up 3
Can you give an example where this conversion is necessary?
Sure! Here's an example where converting a JavaScript object into a JSON string is necessary:
const person = {
name: 'John',
age: 30,
city: 'New York'
};
const jsonString = JSON.stringify(person);
console.log(jsonString);
Output:
{"name":"John","age":30,"city":"New York"}
In this example, we have a JavaScript object 'person' that we want to send to a server or store in a file. By using JSON.stringify() method, we convert the 'person' object into a JSON string representation that can be easily transmitted or stored.
3. How can you convert a JSON string into a JavaScript object?
Use JSON.parse() to turn a JSON string into a JavaScript value:
const text = '{"name":"Ada","age":36}';
const user = JSON.parse(text);
user.name; // "Ada"
Follow-ups interviewers expect:
- It throws on invalid JSON (a
SyntaxError), so wrap untrusted input intry/catch:
try {
const data = JSON.parse(input);
} catch (e) {
// handle malformed JSON
}
- Types don't fully round-trip: a date stored as
"2026-01-01T00:00:00.000Z"comes back as a string, not aDate. Use the reviver (2nd arg) to transform values during parsing:
const obj = JSON.parse(text, (key, value) =>
key === "createdAt" ? new Date(value) : value
);
- Don't hand-roll parsing or use
evalon JSON —JSON.parseis safe and fast. (Worth knowing: there's also a newerJSON.parsesource-text reviver context for things like preservingBigInt.)
Follow-up 1
What is the syntax for this conversion?
The syntax for converting a JSON string into a JavaScript object using JSON.parse() is as follows:
var jsonObject = JSON.parse(jsonString);
Follow-up 2
What is the use of the JSON.parse() method?
The JSON.parse() method is used to parse a JSON string and convert it into a JavaScript object. It is commonly used when receiving data from a server in JSON format and need to work with the data as a JavaScript object.
Follow-up 3
Can you give an example where this conversion is necessary?
Sure! Let's say you have a JSON string representing a person's information:
var jsonString = '{"name":"John", "age":30, "city":"New York"}';
To convert this JSON string into a JavaScript object, you can use the JSON.parse() method:
var person = JSON.parse(jsonString);
console.log(person.name); // Output: John
console.log(person.age); // Output: 30
console.log(person.city); // Output: New York
4. What are the common uses of JSON in web applications?
JSON is the backbone of data exchange in web apps. Common uses:
HTTP APIs (REST / GraphQL): JSON is the standard request and response body. With
fetch, you sendJSON.stringify(body)and read responses viaawait res.json()— no full page reload needed (the modern successor to classic "AJAX").Client-side storage:
localStorage/sessionStorageonly store strings, so objects are stringified going in and parsed coming out.Configuration & tooling: files like
package.json,tsconfig.json, and CI configs use JSON for human-readable, machine-parseable settings.Inter-service messaging & logging: microservices, message queues, and structured logs commonly serialize payloads as JSON.
const res = await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Ada" }),
});
const user = await res.json();
Follow-up to be ready for: because JSON can't carry Date, Map, undefined, or cycles, real APIs agree on conventions (ISO date strings, explicit null) — and for in-memory deep copies of richer data, prefer structuredClone() over the JSON.parse(JSON.stringify(...)) hack.
Follow-up 1
How is JSON used in AJAX?
In AJAX (Asynchronous JavaScript and XML), JSON is commonly used as the data format for sending and receiving data between the web browser and the server. Here's an example of how JSON is used in AJAX:
// Sending a request to the server
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
// Process the response data
}
};
xhr.send();
// Receiving a response from the server
var data = {
'name': 'John Doe',
'age': 30
};
var json = JSON.stringify(data);
xhr.open('POST', 'https://api.example.com/data', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
// Process the response data
}
};
xhr.send(json);
Follow-up 2
How is JSON used in REST APIs?
JSON is the preferred data format for REST APIs (Representational State Transfer Application Programming Interfaces). It is used to structure and transmit data between the client and the server in a standardized and platform-independent way. Here's an example of how JSON is used in a REST API:
GET /api/users HTTP/1.1
Host: api.example.com
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json
{
"users": [
{
"id": 1,
"name": "John Doe",
"email": "[email protected]"
},
{
"id": 2,
"name": "Jane Smith",
"email": "[email protected]"
}
]
}
Follow-up 3
Can you give an example of a real-world application where JSON is used?
One example of a real-world application where JSON is commonly used is a weather application. The weather data, such as temperature, humidity, and wind speed, can be retrieved from a weather API in JSON format. The application can then parse the JSON data and display it to the user in a user-friendly format. Here's an example of a JSON response from a weather API:
{
"location": "New York",
"temperature": 25,
"humidity": 70,
"wind_speed": 10
}
5. What are the limitations of JSON?
JSON is deliberately minimal, and the limitations are a favorite interview topic:
Limited value types. Only string, number, boolean,
null, array, and object are allowed. There's no nativeDate,Map/Set,RegExp,BigInt(it throws), or binary/typed-array support — they must be encoded as strings/arrays and rebuilt manually.undefined, functions, andSymbols are lost. In objects they're omitted; inside arrays they serialize tonull.No comments and strict syntax. Keys must be double-quoted, and trailing commas are illegal — which is why config formats like JSON5 or YAML exist.
No circular references.
JSON.stringifythrows aTypeErroron cycles.No schema / validation. JSON itself doesn't enforce structure or types — you validate separately (e.g. with JSON Schema or a library like Zod).
The practical consequence interviewers want you to draw: the old deep-clone trick JSON.parse(JSON.stringify(obj)) inherits all these flaws — it silently drops functions/undefined, turns Dates into strings, and crashes on cycles. For an in-memory deep copy, use structuredClone(obj), which preserves Date, Map, Set, typed arrays, and circular references (though it still can't clone functions or DOM nodes).
Follow-up 1
What types of data can JSON not represent?
JSON cannot represent complex data types like dates, binary data, or functions. It is limited to simple data types such as strings, numbers, booleans, arrays, and objects.
Follow-up 2
How can these limitations be overcome?
To overcome the limitations of JSON, you can:
Use string representation: For complex data types like dates or binary data, you can convert them to strings before serializing them as JSON. This allows you to represent the data in a JSON-compatible format.
Use custom serialization: For complex data types like functions, you can define custom serialization logic to convert them into JSON-compatible representations. This involves converting the data into a format that can be serialized as a string or a combination of simple data types.
Use data validation libraries: To ensure the validity of the data, you can use data validation libraries or frameworks that provide support for validating JSON data. These libraries can help enforce data integrity and prevent the serialization or deserialization of invalid data.
Use base64 encoding: For representing binary data, you can use base64 encoding to convert the binary data into a string format that can be included in JSON. This allows you to represent binary data in a JSON-compatible way.
Follow-up 3
Are there any alternatives to JSON for data representation?
Yes, there are alternatives to JSON for data representation. Some popular alternatives include:
XML (eXtensible Markup Language): XML is a markup language that allows for structured data representation. It supports complex data types, comments, and data validation. XML is widely used in various industries and has good support in many programming languages.
YAML (YAML Ain't Markup Language): YAML is a human-readable data serialization format. It is designed to be easy to read and write, and supports complex data types, comments, and data validation. YAML is commonly used for configuration files and data exchange between systems.
Protocol Buffers: Protocol Buffers is a language-agnostic binary serialization format developed by Google. It is designed for efficient data storage and transmission, and supports complex data types, data validation, and versioning. Protocol Buffers have good support in many programming languages.
MessagePack: MessagePack is a binary serialization format that is similar to JSON in terms of simplicity and interoperability. It is designed for efficient data storage and transmission, and supports complex data types. MessagePack has good support in many programming languages.
6. What is the difference between a shallow copy and a deep copy, and how do you make each?
A frequent question because it underlies subtle state bugs. A shallow copy duplicates the top level only — nested objects/arrays are still shared by reference. A deep copy recursively duplicates everything, so the copy is fully independent.
const orig = { a: 1, nested: { b: 2 } };
// Shallow — nested is shared
const shallow = { ...orig }; // or Object.assign({}, orig)
shallow.nested.b = 99; // also mutates orig.nested.b !
// Deep — independent
const deep = structuredClone(orig);
deep.nested.b = 99; // orig untouched
The modern tool is structuredClone() (built into browsers and Node 17+), which handles nested objects, arrays, Map, Set, Date, typed arrays, and cyclic references. Follow-ups: the old JSON.parse(JSON.stringify(obj)) trick is lossy — it drops undefined, functions, and Symbols, turns Date into a string, and throws on cycles and BigInt. structuredClone can't clone functions or DOM nodes (throws). For React/Redux, you usually want immutable updates (spread/with/Immer) rather than cloning whole trees.
Live mock interview
Mock interview: JavaScript JSON
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.