JSON interview questions and answers for web, API and QA roles
JSON interview questions check whether you know the exact rules of the format (six value types, double-quoted keys, no comments, no trailing commas) and what happens at the edges when real code parses and serializes it. Expect questions on large numbers losing precision, dates with no native type, duplicate keys, schema validation, patch formats and unsafe merges. The best answers name the specific library behavior and how you would guard against it.
By Evin JohnPublished 9 min read
How JSON shows up in interviews
Few interviews are about JSON alone, yet the topic appears in almost every web, API, mobile, data and test automation loop. A frontend screen may ask you to predict what JSON.stringify prints. A backend round may ask how you would add a field to a response without breaking old clients. A QA or SDET round may hand you a payload and ask what a schema check should reject. Treat JSON as a contract between systems and you will answer most of these well.
- Quick syntax checksIs this document valid? Which value types exist? Why does a single quote or a trailing comma fail?
- Output predictionShort snippets in JavaScript or Python where the printed result depends on a parsing or serialization rule.
- API designShape a response, name fields, handle nulls versus missing keys, evolve the contract and paginate.
- Debugging and securityA number that changed in transit, a client that crashes on a new field, a merge that polluted an object prototype.
JSON fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What value types does JSON support? | Grammar | Object, array, string, number, boolean and null. Nothing else: no date, no undefined, no binary, no comment. |
Is {name: 'Ada'} valid JSON? | Strictness | No. Keys must be double-quoted strings and strings use double quotes. It is a valid JavaScript object literal, which is a different thing. |
| Why does a trailing comma break a document? | Parser behavior | The grammar forbids it. Lenient formats such as JSON5 or JSONC (used by some editor and compiler config files) accept it, standard parsers do not. |
| How do you represent a date? | Missing types | As a string, most often ISO 8601 in UTC such as 2026-03-01T09:30:00Z, or as epoch milliseconds. Pick one per API and document it. |
| What is the difference between null and a missing key? | Semantics | Null says the field exists and has no value; absence says nothing was sent. For partial updates that difference decides whether you clear a field or leave it alone. |
| Which character encoding should JSON use? | Interchange | The current RFC requires UTF-8 for JSON exchanged between systems. Non-ASCII characters may appear directly or as \u escapes. |
| What is the media type? | HTTP | application/json. Sending it as text/plain or form data is a common cause of a server ignoring the body. |
| JSON or XML for a new API? | Trade-offs | JSON is smaller and maps directly to objects in most languages. XML still fits document formats, mixed content and older enterprise contracts with XSD and namespaces. |
| Does key order in an object matter? | Spec versus practice | The spec treats objects as unordered, so code must not depend on order. Many parsers preserve it, which is why tests that compare raw strings are brittle. |
| Can the top level be an array or a plain value? | Grammar | Yes, any value may be the top level under the current standard. Very old parsers required an object or array. |
Parsing and serialization questions
These are the questions where people who use JSON daily still slip, because the behavior lives in the parser, not the format. The snippet below runs in Node.js and covers four classic traps in a few lines.
const raw = '{"id": 9007199254740993, "at": "2026-03-01T09:30:00Z"}';
console.log(JSON.parse(raw).id); // 9007199254740992, precision lost
const safe = raw.replace(/"id":\s*(\d+)/, (_, digits) => '"id":"' + digits + '"');
console.log(JSON.parse(safe).id); // "9007199254740993" as a string
const withDates = JSON.parse(raw, (key, value) =>
key === "at" ? new Date(value) : value);
console.log(withDates.at instanceof Date); // true
console.log(JSON.stringify({ a: undefined, b: () => 1, c: NaN, d: [undefined] }));
// {"c":null,"d":[null]}
try { JSON.stringify({ n: 10n }); } catch (e) { console.log(e.name); } // TypeError- Why did the ID change after parsing? JavaScript numbers are 64-bit floats, so integers above
Number.MAX_SAFE_INTEGER(2^53 minus 1) cannot all be represented. The fix belongs in the contract: send large IDs as strings. Regex rewriting, as in the demo, is only a stopgap. - What does JSON.stringify do with undefined, functions and NaN? Object properties holding undefined or functions are dropped; inside arrays they become null. NaN and Infinity become null. BigInt throws unless you supply a toJSON or replacer.
- What are the replacer and reviver arguments for? The replacer filters or transforms values on the way out (hide a password field, convert a Map). The reviver transforms values on the way in (strings back into dates).
- What does toJSON do? If an object has a toJSON method, stringify serializes its return value instead. Date uses this, which is why a Date becomes an ISO string.
- Is `JSON.parse(JSON.stringify(x))` a good deep copy? Only for plain data. It loses dates, Maps, Sets, undefined and class prototypes, and it throws on cycles.
structuredCloneis the better built-in for most of those cases. - How do you serialize an object with a circular reference? Break the cycle with a replacer that tracks seen objects, or model the data as IDs plus references so the payload is a tree.
- What happens with duplicate keys? The spec says names should be unique but does not forbid duplicates, and most parsers keep the last value. That gap has caused real security bugs when two components read different copies.
import json
from decimal import Decimal
print(json.dumps({"x": float("nan")})) # {"x": NaN} (not valid JSON)
try:
json.dumps({"x": float("nan")}, allow_nan=False)
except ValueError as e:
print("rejected:", e)
def no_dupes(pairs):
keys = [k for k, _ in pairs]
if len(keys) != len(set(keys)):
raise ValueError(f"duplicate keys: {keys}")
return dict(pairs)
print(json.loads('{"a": 1, "a": 2}')) # {'a': 2}, last one wins
try:
json.loads('{"a": 1, "a": 2}', object_pairs_hook=no_dupes)
except ValueError as e:
print("rejected:", e)
print(json.loads('{"price": 19.99}', parse_float=Decimal)) # Decimal('19.99')
print(json.dumps({"city": "Zürich"}, ensure_ascii=False)) # keeps the ü- Why parse money with Decimal? A binary float cannot hold most decimal fractions exactly, so totals drift. Parsing into Decimal, or sending minor units as integers, keeps amounts exact.
- What does ensure_ascii change? By default Python escapes every non-ASCII character as
\usequences. Turning it off keeps readable UTF-8, which is smaller for many languages. - How do Java libraries handle an unknown field? Jackson's ObjectMapper fails on unknown properties by default; you relax it per class with
@JsonIgnoreProperties(ignoreUnknown = true)or globally on the mapper. Framework defaults can differ, so check what your stack configures.
Intermediate questions: schemas, paths and patches
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is JSON Schema used for? | Validation | Describing required fields, types, formats, enums and ranges so requests can be validated at the edge and docs or types generated from one source. Know which draft your validator supports. |
What does additionalProperties: false do, and when is it risky? | Strict versus tolerant | It rejects fields the schema does not list. Good for requests you accept; risky on responses you consume, because a provider adding a field would break you. |
| JSON Pointer versus JSONPath? | Addressing | A pointer such as /orders/0/total names exactly one location. JSONPath is a query language that can match many nodes with wildcards and filters. |
| JSON Patch versus JSON Merge Patch? | Partial updates | Patch is a list of operations (add, remove, replace, move, copy, test) and can edit array items. Merge Patch sends a partial document where null means delete, which is simpler but cannot set a field to null or edit one array element. |
| What are JSON Lines? | Streaming data | One complete JSON value per line. Logs, exports and bulk APIs use it because a reader can process line by line and a bad record does not spoil the whole file. |
| How would you parse a 2 GB JSON file? | Memory | Not with a whole-document parse. Use a streaming or event parser (Jackson's streaming API, ijson in Python, a stream parser in Node), or convert to JSON Lines first. |
| How do you diff two JSON documents in a test? | Testing | Parse both and compare structures, ignoring key order and volatile fields like timestamps. String comparison fails on formatting and order differences. |
| How does a database store JSON? | Storage | Many engines offer a JSON column type with operators and indexes. In PostgreSQL, jsonb stores a parsed binary form that can be indexed, see PostgreSQL interview questions. |
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["sku", "quantity", "unitPriceMinor", "orderedAt"],
"properties": {
"sku": { "type": "string", "pattern": "^[A-Z0-9-]{4,20}$" },
"quantity": { "type": "integer", "minimum": 1 },
"unitPriceMinor": { "type": "integer", "minimum": 0 },
"currency": { "type": "string", "enum": ["USD", "EUR", "INR"] },
"orderedAt": { "type": "string", "format": "date-time" }
},
"additionalProperties": false
}Senior and scenario questions
- A mobile client crashes after the backend adds a field. What went wrong and how do you prevent it? The client deserializer was strict about unknown fields. Clients should ignore what they do not know, servers should only add optional fields within a version, and contract tests should run on both sides.
- How do you rename a field in a public API? Add the new name, send both for a deprecation window, track which clients still read the old one, then remove it in a new version. Never change a field's type in place.
- What is prototype pollution and how does JSON lead to it?
JSON.parsehappily creates a key named__proto__. A naive recursive merge that copies keys onto a target can then write ontoObject.prototype, changing every object in the process. Skip dangerous keys, merge into objects created withObject.create(null), or use a vetted library. - Why not build JSON by string concatenation? A quote or backslash in user data breaks the document or injects fields. Always build a structure and serialize it with a library.
- What is the risk of embedding JSON inside an HTML script tag? A value containing
</script>closes the tag early and opens an injection point. Escape<as\u003cwhen you inline data into a page. - You need to sign a JSON payload. What is the catch? Two equivalent documents can differ in whitespace, key order and number formatting, so signatures need a canonical form (for example the JSON Canonicalization Scheme) or must cover the exact bytes sent, as JWS does.
- Responses are slow and large. What do you look at? Over-fetching (fields the client never reads), deep nesting, repeated objects that could be referenced, pagination, and compression with gzip or Brotli. Measure serialization time separately from network time.
- Should an error response use a standard shape? Yes. Problem Details for HTTP APIs gives a type, title, status, detail and instance, so clients can handle errors in one place.
- When would you choose a binary format over JSON? High-volume internal traffic where size and parse time dominate, or where a strict schema is wanted: Protocol Buffers, Avro or MessagePack. Keep JSON at public edges where readability matters.
Fictional example
- Interviewer
- Customers occasionally see totals one cent different from the invoice. The API returns JSON. Where do you start?
- Candidate
- My first suspect is floating point. If prices travel as decimals like 19.99 and someone sums them as doubles, rounding drifts. I would grab a failing order and trace the value at each hop: the database column type, what the serializer writes, what the client parses into, and where the sum happens. The durable fix is to send integer minor units, 1999 with a currency code, or decimal strings parsed into a decimal type. I would add a schema rule that the price is an integer and a test with amounts that are known to drift, so the bug cannot come back quietly.
A one-week JSON practice plan
- Days 1 and 2: write ten tiny documents by hand that are almost valid (single quotes, a trailing comma, a comment, NaN) and say why each fails before you run a parser on it.
- Day 3: in Node.js, reproduce the large-ID problem, a reviver for dates and a replacer that hides secrets. Explain each result aloud.
- Day 4: in Python or Java, parse money into a decimal type and turn on strict handling of unknown or duplicate fields.
- Day 5: write a JSON Schema for one real request in an API you know and test it against five bad payloads.
- Days 6 and 7: design a field rename and a partial update with both Patch and Merge Patch, then rehearse the senior scenarios with a timer.
JSON questions sit next to API and language topics: REST API interview questions covers status codes and versioning, JavaScript interview questions covers the runtime behind JSON.parse, and API testing interview questions covers checking payloads in Postman and REST Assured. Java developers who map JSON straight into entities may also want JPA interview questions.
Output prediction questions reward slow, precise reasoning, which is hard to judge from memory after a mock. Natively, an AI interview assistant for Mac and Windows, transcribes your practice round on the computer so you can check whether you named the rule (MAX_SAFE_INTEGER, the reviver, last-key-wins) or just guessed the output. In practice it can read a snippet or a payload from a screenshot and suggest what to explain, and with Pro or the free trial it uses your résumé and the job description you add. Transcripts and notes stay available to review.
Questions people ask
What JSON questions are asked in interviews?
The six value types, why single quotes and trailing commas are invalid, null versus a missing key, how dates and large numbers are sent, what JSON.stringify drops, JSON Schema validation, and how to evolve an API payload without breaking clients.
Why does a large ID change after JSON.parse in JavaScript?
JavaScript numbers are 64-bit floats, so integers above 2^53 minus 1 cannot all be represented exactly. Send large IDs as strings in the API contract.
What is the difference between JSON Patch and JSON Merge Patch?
JSON Patch is a list of operations such as add, remove and replace, and can edit single array items. Merge Patch sends a partial document where null deletes a field, which is simpler but less precise.
Is JSON the same as a JavaScript object?
No. JSON is a text format with stricter rules: double-quoted keys and strings, no comments, no trailing commas, no functions or undefined. A JavaScript object literal allows all of those.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
