Back to interview questions

100+ JSON Interview Questions and Answers

100+ JSON Interview Questions and Answers

Explore 120 JSON interview questions and answers on syntax, serialization, JSON Schema, patches, Unicode, streaming, interoperability and API security.

Explore 120 JSON interview questions and answers on syntax, serialization, JSON Schema, patches, Unicode, streaming, interoperability and API security.

By

Team Sherlock.sh

Add Sherlock as a preferred source on Google

JSON interviews should reveal whether a candidate can exchange structured data without losing its meaning. Familiar braces and brackets hide important choices about numbers, missing fields, Unicode and parser behavior. Recruiters should assess whether candidates can distinguish valid syntax from an interoperable contract and recognize where validation, transport or application logic must provide additional guarantees.

These 100+ JSON Interview Questions and Answers cover 120 questions across beginner, intermediate and experienced levels. They progress from JSON values and serialization to JSON Schema, pointers and patches, streaming, canonicalization and secure API contracts. The examples compare specification rules with concrete JavaScript and Python behavior rather than assuming every parser behaves alike.

How can recruiters test JSON expertise beyond recognizing a well-formed payload?

Give the candidate a small document and ask what survives a parse-and-serialize round trip. Then introduce a large integer, a duplicate name or a patch that removes a required field. Strong candidates identify the applicable contract, explain the exact outcome and propose a test that catches differences between producers and consumers.

Sherlock AI helps hiring teams assess signals of potential AI cheating, deepfakes, impersonation and unauthorized assistance during remote interviews. Combine those signals with payload walkthroughs and follow-up questions about validation, interoperability and error handling. Use them as context for a fair review alongside demonstrated understanding, rather than conclusive proof of misconduct.

JSON Interview Questions

Select questions that match the role’s API, data-processing and integration responsibilities. Give candidates the relevant parser, schema dialect and transport assumptions so they can explain precise outcomes. The complete question bank comes first, followed by identically numbered answers.

JSON Interview Questions for Beginners

Check whether candidates can identify valid JSON and explain how common values map into a programming language. Ask for exact results, including what happens to missing, null and numeric values.

  1. What is JSON used for?

  2. How does JSON differ from a JavaScript object literal?

  3. What are JSON’s six value types?

  4. When should JSON use an object rather than an array?

  5. Can a valid JSON document contain only a number or a string?

  6. Why must JSON strings and object names use double quotes?

  7. How are quotes, backslashes and line breaks represented inside a JSON string?

  8. Can a JSON string contain an unescaped control character?

  9. How do Unicode text and UTF-8 relate to JSON?

  10. What number forms are valid JSON?

  11. Are true, false and null case-sensitive in JSON?

  12. Are comments and trailing commas allowed in standard JSON?

  13. Which whitespace is allowed between JSON tokens?

  14. Why should duplicate object member names be avoided?

  15. Does the order of JSON object members carry meaning?

  16. Does the order of elements in a JSON array matter?

  17. How does null differ from a missing object member?

  18. Why are a JSON number and a numeric-looking string different?

  19. What is the difference between parsing and serialization?

  20. How does JSON.parse handle valid and invalid input in JavaScript?

  21. What does JSON.stringify do with unsupported JavaScript values?

  22. How do json.loads and json.dumps work in Python?

  23. How are JSON booleans and null represented in programming languages?

  24. Why might a JSON round trip change a language-specific type?

  25. How should dates and timestamps be represented in JSON?

  26. How can binary data be carried in JSON?

  27. Why can a large JSON integer lose precision in JavaScript?

  28. Can JSON.stringify serialize a JavaScript BigInt directly?

  29. What changes when JSON is pretty-printed or minified?

  30. Does JSON string escaping make data safe to insert into HTML?

  31. What does the application/json media type communicate?

  32. How should a JSON document become an HTTP request body?

  33. How does valid JSON syntax differ from valid application data?

  34. What is JSON Schema used for?

  35. Does listing a field in properties make it required?

  36. How does additionalProperties control unexpected object members?

  37. When would you use enum instead of const in JSON Schema?

  38. How do you validate objects inside a JSON array?

  39. What makes a JSON API error useful to a client?

  40. Why is JSON not a database or a complete communication protocol?

JSON Interview Questions for Intermediate

Explore schema composition, patch semantics and stream processing. Ask which assumptions a validator or parser enforces and which belong to the application contract.

  1. Why should a JSON Schema declare its dialect with $schema?

  2. How do $id and $ref affect reference resolution?

  3. How does $defs support reusable constraints without automatically applying them?

  4. Why is allOf not object-oriented inheritance?

  5. How do anyOf and oneOf differ when their branches overlap?

  6. How do if, then and else express a conditional document rule?

  7. When should you use dependentRequired instead of dependentSchemas?

  8. How does unevaluatedProperties differ from additionalProperties?

  9. How do prefixItems and items describe tuple-like arrays in Draft 2020-12?

  10. How do contains, minContains and maxContains constrain matching array elements?

  11. What does uniqueItems compare in arrays of objects?

  12. Why can multipleOf reveal numeric precision differences between validators?

  13. Does JSON Schema string length count bytes or visible characters?

  14. Why should a whole-string JSON Schema pattern usually be anchored?

  15. Does the format keyword always reject an invalid email or date?

  16. Do readOnly and writeOnly automatically prevent fields from crossing an API boundary?

  17. Does a JSON Schema default insert a missing property?

  18. How do you assess whether a schema change is backward compatible?

  19. How do JSON Pointer escapes identify keys containing slashes or tildes?

  20. How does JSON Pointer interpret array indices and the dash token?

  21. Why must JSON Patch operations be evaluated in sequence?

  22. How can a JSON Patch test operation detect a stale edit?

  23. How do add, replace and remove differ for objects and arrays?

  24. What is the difference between JSON Patch move and copy?

  25. Why does null have special meaning in JSON Merge Patch?

  26. How does JSON Merge Patch update an array?

  27. How can a JavaScript replacer and reviver implement an explicit serialization contract?

  28. How can toJSON change the output of JSON.stringify?

  29. How does JavaScript serialize undefined and nonfinite numeric values?

  30. How do you make Python reject nonstandard NaN and Infinity JSON values?

  31. How can Python detect duplicate object names while parsing JSON?

  32. What does parse_float=Decimal preserve, and what does it not solve?

  33. What does NDJSON framing require from producers and consumers?

  34. How do RFC 7464 JSON text sequences differ from newline-delimited JSON?

  35. Why cannot an incremental JSON parser treat every network chunk as a complete document?

  36. How would you process a very large JSON array with bounded memory?

  37. Why must an HTTP PATCH endpoint distinguish patch media types?

  38. What should a paginated JSON response make explicit?

  39. How should a validation error identify a deeply nested failing value?

  40. How does OpenAPI 3.1 align with JSON Schema without making every object a schema?

JSON Interview Questions for Experienced

Probe interoperability and security across multiple services, runtimes and trust boundaries. Ask how a proposed design handles ambiguous inputs, signature verification and evolving contracts.

  1. How can escaped object names bypass a raw-text duplicate-key check?

  2. What does RFC 8785 canonicalization provide beyond sorting object keys?

  3. When should a signature cover original JSON bytes versus canonical JSON?

  4. Why can JCS be unsuitable for arbitrary-precision financial numbers?

  5. Does JSON canonicalization normalize Unicode strings?

  6. How should a service handle lone surrogate escapes?

  7. How should a JSON endpoint handle UTF-8 and byte-order marks?

  8. Where should JSON depth and size limits be enforced?

  9. How can numeric literals exhaust resources even when JSON syntax is valid?

  10. Does JSON.parse itself cause prototype pollution?

  11. How can schema reference resolution become an SSRF risk?

  12. Why can a schema pattern become a denial-of-service issue?

  13. How should authorization work for JSON Patch paths?

  14. Why can a JSON Patch test fail when host-language equality says two values match?

  15. Can an empty JSON Merge Patch change a scalar or array into an object?

  16. How do you evolve a JSON contract with independently deployed producers and consumers?

  17. How should an audit pipeline distinguish a number’s value from its original spelling?

  18. Can a JSON round trip preserve negative zero?

  19. What makes a date-time string an interoperable contract?

  20. Do contentEncoding and contentMediaType validate embedded binary content?

  21. How is a JSON-LD context different from a JSON Schema?

  22. When would you choose CBOR instead of JSON?

  23. Why should JSON5 support stop at an explicit boundary?

  24. Why is JSONP not a substitute for a JSON API with CORS?

  25. How can JSON logging still allow misleading or unsafe log output?

  26. Why is valid JSON not automatically safe inside an HTML script element?

  27. How can a streaming import offer all-or-nothing visibility without buffering the whole JSON file?

  28. Why must a JSON text-sequence parser reject an unterminated top-level number?

  29. Why should a signed JSON envelope bind its schema and intended use?

  30. When do dynamic references matter in composed JSON Schemas?

  31. Why can stopping after the first successful anyOf branch break unevaluatedProperties?

  32. Should clients depend on the first validation error returned?

  33. What should a property-based JSON test corpus explore?

  34. Why can a successful serialize-parse round trip hide a bug?

  35. How would you build a useful differential-parser harness?

  36. What should be included in a schema-validation cache key?

  37. How can contract telemetry remain useful without storing private payloads?

  38. Why does sending the same JSON twice not guarantee an idempotent API call?

  39. What makes a JSON data migration auditable and reversible?

  40. How would you trace a serialization failure across several services?

JSON Interview Questions and Answers

Syntax discussion follows RFC 8259, and schema examples use JSON Schema 2020-12 unless stated otherwise. JSON is distinct from JavaScript object literals and Python dictionaries. Language examples identify their execution context; acceptance by one parser does not establish interoperability across all implementations.

JSON Interview Questions and Answers for Beginners

These answers establish JSON syntax and serialization behavior, with small examples that distinguish the data format from a language’s in-memory objects.

1. What is JSON used for?

JSON is a text-based data-interchange format standardized by RFC 8259. It represents structured values that different systems can exchange without sharing a programming language. It defines the representation, not what a business field means or what an application must do with it.

For example, a service can send an order identifier and an array of items to another service. Both sides still need to agree on field names, types and units. A document being valid JSON does not prove that the order exists, that its totals are correct or that the receiver is authorized to process it.

2. How does JSON differ from a JavaScript object literal?

A JavaScript object literal is source-code syntax used to create an object. JSON is data text with stricter rules, including double-quoted member names and no functions or ordinary JavaScript expressions. Similar appearance does not make the two interchangeable.

const value = { name: 'A', active: true };
console.log(JSON.stringify(value));
const value = { name: 'A', active: true };
console.log(JSON.stringify(value));
const value = { name: 'A', active: true };
console.log(JSON.stringify(value));

The object literal is legal JavaScript, and serialization produces {"name":"A","active":true}. The original literal with an unquoted key and single-quoted string is not itself JSON text. Use a JSON parser for JSON data rather than evaluating it as program code.

3. What are JSON’s six value types?

JSON supports objects, arrays, strings, numbers, booleans and null. These are format-level categories; a language may map them into its own runtime types. JSON does not have separate built-in types for dates, functions, undefined values or binary buffers.

JSON

{"metadata": {}, "tags": [], "label": "box", "quantity": 3, "active": true, "note": null}
{"metadata": {}, "tags": [], "label": "box", "quantity": 3, "active": true, "note": null}
{"metadata": {}, "tags": [], "label": "box", "quantity": 3, "active": true, "note": null}

This object demonstrates all six categories through its members. The quantity is a number, while the label is a string even if it could contain digits. The empty object and array are distinct structures, and null is an explicit value rather than an omitted member.

4. When should JSON use an object rather than an array?

An object associates string names with values, while an array stores an ordered sequence of values. Choose based on the contract: named attributes belong naturally in an object, and a sequence of records belongs naturally in an array. JSON permits mixed array element types, although an application schema may restrict them.

JSON

{"status": "ready", "items": [{"code": "A"}, {"code": "B"}]}
{"status": "ready", "items": [{"code": "A"}, {"code": "B"}]}
{"status": "ready", "items": [{"code": "A"}, {"code": "B"}]}

The object has a named status and an ordered list of two items. An empty items array would mean no elements in the list; it would not mean that the items field was absent. Avoid using numbered object keys to imitate an array unless those keys have an independent identifier meaning.

5. Can a valid JSON document contain only a number or a string?

Yes. Under RFC 8259, a JSON text can contain any JSON value at the top level, including a number, string, boolean or null. It is not restricted to an object or array. An API may impose a narrower contract, but that is an application rule.

console.log(JSON.parse('42'));
console.log(JSON.parse('"ready"'));
console.log(JSON.parse('42'));
console.log(JSON.parse('"ready"'));
console.log(JSON.parse('42'));
console.log(JSON.parse('"ready"'));

Parsing the top-level number produces 42, and parsing the quoted JSON string produces the JavaScript string ready. A receiver expecting an object should validate that expectation after parsing; successful parsing alone does not establish the required top-level shape.

6. Why must JSON strings and object names use double quotes?

Double quotes delimit strings in JSON, including the string names of object members. Single-quoted strings are not part of the JSON grammar, even when a programming language allows them. The outer string used in source code to hold JSON text follows the host language’s separate rules.

const text = '{"name":"Mira"}';
console.log(JSON.parse(text).name);
const text = '{"name":"Mira"}';
console.log(JSON.parse(text).name);
const text = '{"name":"Mira"}';
console.log(JSON.parse(text).name);

Here the JavaScript source uses single quotes around the entire JSON text, while the JSON inside uses double quotes. Parsing returns the name Mira. Confusing those two layers often leads to a document that looks reasonable in code but is rejected by a JSON parser.

7. How are quotes, backslashes and line breaks represented inside a JSON string?

JSON uses defined escape sequences to represent characters that cannot appear literally in a string or need escaping. A quotation mark uses \", a backslash uses \\ and a line feed can use \n. Escape characters are part of the text representation, not necessarily extra characters in the decoded value.

JSON

{"message": "Say \"ready\"\nThen continue", "path": "C:\\work\\note.txt"}
{"message": "Say \"ready\"\nThen continue", "path": "C:\\work\\note.txt"}
{"message": "Say \"ready\"\nThen continue", "path": "C:\\work\\note.txt"}

After parsing, message contains quotation marks and one line feed, while path contains ordinary backslashes. When embedding this JSON in another programming-language string, another layer of escaping may be needed. Prefer a serializer instead of manually counting backslashes for dynamically constructed data.

8. Can a JSON string contain an unescaped control character?

Control characters U+0000 through U+001F must be escaped inside JSON strings. A literal tab or line feed between opening and closing quotation marks is therefore invalid JSON string content. This restriction differs from permitted whitespace between JSON tokens.

Use \n to encode a line feed within a string, or let the serializer produce the escape. A multiline pretty-printed document is valid because its formatting line breaks occur outside strings. Some permissive parser modes accept extensions, but that does not make their input portable strict JSON.

9. How do Unicode text and UTF-8 relate to JSON?

JSON strings represent Unicode text, while UTF-8 is the byte encoding required by RFC 8259 for JSON exchanged outside a closed ecosystem. A character can often appear directly or through a Unicode escape without changing the decoded string. Character count and byte length are different measurements.

const direct = JSON.parse('"é"');
const escaped = JSON.parse('"\u00e9"');
console.log(direct === escaped);
console.log(Buffer.byteLength(direct, 'utf8'));
const direct = JSON.parse('"é"');
const escaped = JSON.parse('"\u00e9"');
console.log(direct === escaped);
console.log(Buffer.byteLength(direct, 'utf8'));
const direct = JSON.parse('"é"');
const escaped = JSON.parse('"\u00e9"');
console.log(direct === escaped);
console.log(Buffer.byteLength(direct, 'utf8'));

Both parses produce the same character, so equality is true. The UTF-8 encoding of that character uses two bytes, giving the second output 2. Correct encoding does not automatically normalize visually similar Unicode sequences; an application that needs normalization must define that separately.

10. What number forms are valid JSON?

JSON numbers can have an optional minus sign, an integer part, an optional fractional part and an optional exponent. Leading plus signs, unnecessary leading zeroes, hexadecimal notation, NaN and Infinity are not JSON number syntax. The grammar does not guarantee that every parser preserves every numeric value exactly.

JSON

[0, -7, 1.25, 6e2]
[0, -7, 1.25, 6e2]
[0, -7, 1.25, 6e2]

These examples represent zero, a negative integer, a decimal and an exponent form. Values such as 01 or 1. are invalid number forms. If the receiver needs exact money or a very large identifier, the application contract must also specify representation and precision rather than relying solely on valid syntax.

11. Are true, false and null case-sensitive in JSON?

Yes. JSON’s literal values are lowercase true, false and null. Spellings such as True, FALSE and None belong to other contexts or are simply invalid JSON. Quoting a literal also changes its type into a string.

JSON

[true, false, null, "false"]
[true, false, null, "false"]
[true, false, null, "false"]

The first two values are booleans and the third is null. The final value is the string "false", not the boolean false. A consumer should not treat arbitrary nonempty strings as Boolean configuration values without an explicit parsing rule.

12. Are comments and trailing commas allowed in standard JSON?

No. RFC 8259 JSON does not include comment syntax or trailing commas after the last object member or array element. Formats such as JSON-with-comments are separate conventions, and a tool accepting them does not establish compatibility with strict JSON receivers.

for (const text of ['[1,2,]', '{"a":1 // note\n}']) {
  try { JSON.parse(text); console.log(false); }
  catch (error) { console.log(error instanceof SyntaxError); }
}
for (const text of ['[1,2,]', '{"a":1 // note\n}']) {
  try { JSON.parse(text); console.log(false); }
  catch (error) { console.log(error instanceof SyntaxError); }
}
for (const text of ['[1,2,]', '{"a":1 // note\n}']) {
  try { JSON.parse(text); console.log(false); }
  catch (error) { console.log(error instanceof SyntaxError); }
}

Both strings in the example are rejected by JavaScript’s JSON parser, so the output is true twice. The example catches SyntaxError instead of depending on the wording of an error message, which can vary between runtimes. Remove comments from the exchanged data or place explanatory text in a defined data field.

13. Which whitespace is allowed between JSON tokens?

JSON permits space, horizontal tab, line feed and carriage return as insignificant whitespace around structural tokens. It does not treat every Unicode spacing character as interchangeable formatting. Whitespace inside a string remains part of the value.

A compact object and a version indented with spaces and line breaks can represent the same data. In contrast, adding a space inside a customer code changes that code. When cleaning input, do not indiscriminately remove whitespace from the whole text, because doing so can alter string values and corrupt the data.

14. Why should duplicate object member names be avoided?

RFC 8259 says object member names should be unique for interoperable behavior. Parsers differ in how they expose duplicates: some keep one value, some reject them and others can expose all pairs. Do not build a security or business rule around every receiver resolving duplicates identically.

const value = JSON.parse('{"limit":1,"limit":2}');
console.log(value.limit);
const value = JSON.parse('{"limit":1,"limit":2}');
console.log(value.limit);
const value = JSON.parse('{"limit":1,"limit":2}');
console.log(value.limit);

JavaScript’s JSON.parse keeps the later value in this example and prints 2. That is a demonstrated behavior of this parser, not a universal JSON requirement. Prefer rejecting duplicate names at a boundary that supports such checking rather than silently accepting an ambiguous request.

15. Does the order of JSON object members carry meaning?

A JSON object is a collection of named members, and applications should not use member order to encode a business sequence. Runtime objects may expose a particular enumeration order, but that is not a portable substitute for a field defining the intended sequence.

Objects containing name and quantity in different textual orders can convey the same application data. Their text bytes still differ, which matters for hashes or signatures unless an agreed canonicalization is used. When order itself matters, use an array or an explicit ordering field rather than relying on the serializer’s current output.

16. Does the order of elements in a JSON array matter?

Yes. An array is an ordered sequence, and repeated values are allowed. Reordering its elements changes the sequence even when it contains the same values. Applications can choose to interpret a particular array as a set, but that must be part of their contract.

For a list of workflow steps, ["review","approve"] does not mean the same sequence as ["approve","review"]. Likewise, removing repeated elements may lose information from a list of observations. Do not sort or deduplicate every array merely to make a document look cleaner.

17. How does null differ from a missing object member?

Null is an explicit JSON value, while a missing member is not present at all. An API can assign different meanings to those states, such as clearing a stored note versus leaving the existing note unchanged. JSON itself does not choose those application semantics.

const a = JSON.parse('{"note":null}');
const b = JSON.parse('{}');
console.log(Object.hasOwn(a, 'note'));
console.log(Object.hasOwn(b, 'note'));
const a = JSON.parse('{"note":null}');
const b = JSON.parse('{}');
console.log(Object.hasOwn(a, 'note'));
console.log(Object.hasOwn(b, 'note'));
const a = JSON.parse('{"note":null}');
const b = JSON.parse('{}');
console.log(Object.hasOwn(a, 'note'));
console.log(Object.hasOwn(b, 'note'));

The example prints true and false: the first object has a note member even though its value is null, while the second does not have that member. Test presence separately from value when the distinction matters; treating both as a false-like value can discard the caller’s intent.

18. Why are a JSON number and a numeric-looking string different?

The number 12 and the string "12" have different types. A parser should preserve that distinction in its language mapping rather than infer that every string containing digits is a number. Identifiers often need a string representation even when they contain only digits.

An account code such as "0012" retains leading zeroes and is not naturally an arithmetic quantity. Converting it to 12 loses that representation. Define the field’s type and meaning in the schema or API contract instead of applying broad automatic coercion to all incoming strings.

19. What is the difference between parsing and serialization?

Parsing converts JSON text into a language’s values. Serialization converts supported language values into JSON text. Neither operation by itself verifies business meaning, and the mapping may lose information for types that JSON does not represent.

For example, parsing an order makes its fields accessible to code, while serializing it prepares a representation for storage or transfer. Repeatedly serializing an already serialized string adds another layer of quotation and escaping rather than creating a second equivalent object. Keep clear whether a variable holds text or parsed data.

20. How does JSON.parse handle valid and invalid input in JavaScript?

JSON.parse parses a JSON text and returns the corresponding JavaScript value. Invalid syntax raises a SyntaxError. A successful parse still needs any required shape and value checks before the application trusts its contents.

const value = JSON.parse('{"quantity":3}');
console.log(value.quantity);
try { JSON.parse('{quantity:3}'); }
catch (error) { console.log(error instanceof SyntaxError); }
const value = JSON.parse('{"quantity":3}');
console.log(value.quantity);
try { JSON.parse('{quantity:3}'); }
catch (error) { console.log(error instanceof SyntaxError); }
const value = JSON.parse('{"quantity":3}');
console.log(value.quantity);
try { JSON.parse('{quantity:3}'); }
catch (error) { console.log(error instanceof SyntaxError); }

The output is 3 for the valid quantity and true for the caught malformed input. Catch errors at an appropriate input boundary without hiding them as an empty successful object. Otherwise the application may continue with defaults after a genuinely invalid request.

21. What does JSON.stringify do with unsupported JavaScript values?

JSON.stringify serializes supported values, but it does not preserve every JavaScript type. For ordinary object properties, undefined values are omitted; in an array, undefined becomes null. A top-level undefined value produces undefined rather than a JSON text.

const value = { note: undefined, items: [undefined] };
console.log(JSON.stringify(value));
const value = { note: undefined, items: [undefined] };
console.log(JSON.stringify(value));
const value = { note: undefined, items: [undefined] };
console.log(JSON.stringify(value));

The output is {"items":[null]}. This difference matters when an API distinguishes an absent field from an explicit null. Validate the object before serialization when silently dropping a property would change a request’s meaning.

22. How do json.loads and json.dumps work in Python?

json.loads parses text into Python values, while json.dumps returns a JSON string. The similarly named load and dump functions operate with file-like objects. Use the function that matches the input or output you actually have.

import json
value = json.loads('{"quantity":4,"active":true}')
print(value['quantity'])
print(json.dumps(value, separators=(',', ':'), allow_nan=False))
import json
value = json.loads('{"quantity":4,"active":true}')
print(value['quantity'])
print(json.dumps(value, separators=(',', ':'), allow_nan=False))
import json
value = json.loads('{"quantity":4,"active":true}')
print(value['quantity'])
print(json.dumps(value, separators=(',', ':'), allow_nan=False))

This prints 4 followed by {"quantity":4,"active":true}. The separators setting only changes formatting. Python’s default serializer permits non-finite floats as an extension; use allow_nan=False when producing standards-compliant JSON and reject unsupported numeric values rather than relying on other parsers to accept them.

23. How are JSON booleans and null represented in programming languages?

JSON uses the literal names true, false, and null. A parser maps them to the receiving language’s values: Python uses True, False, and None, whereas JavaScript uses true, false, and null. Their spelling in source code is not a reason to edit the JSON text manually.

import json
value = json.loads('{"enabled":false,"note":null}')
print(value['enabled'] is False)
print(value['note'] is None)
import json
value = json.loads('{"enabled":false,"note":null}')
print(value['enabled'] is False)
print(value['note'] is None)
import json
value = json.loads('{"enabled":false,"note":null}')
print(value['enabled'] is False)
print(value['note'] is None)

The Python example prints True and True. The string "false" remains a nonempty string, so checking its truthiness would not give the meaning of the JSON boolean false. Parse the document and then check the field’s required type instead of using text replacement or loose truthiness tests.

24. Why might a JSON round trip change a language-specific type?

A round trip preserves only the information represented by the chosen JSON mapping. JSON has arrays but no tuple type, objects but no general map with arbitrary key types, and no built-in class identity. Serializing and parsing is therefore not a universal cloning mechanism.

import json
original = (2, 5)
restored = json.loads(json.dumps(original))
print(type(restored).__name__)
print(restored == [2, 5])
import json
original = (2, 5)
restored = json.loads(json.dumps(original))
print(type(restored).__name__)
print(restored == [2, 5])
import json
original = (2, 5)
restored = json.loads(json.dumps(original))
print(type(restored).__name__)
print(restored == [2, 5])

The example prints list and True. The elements survived, but the Python tuple became a list. If immutable tuples or custom classes are important, define a reconstruction rule and validate the input; do not assume the parser can infer the original runtime type.

25. How should dates and timestamps be represented in JSON?

JSON has no date or timestamp value type. APIs commonly use strings with an explicitly documented date-time format and timezone rule, or numbers with a documented epoch and unit. A field name such as timestamp does not tell a consumer whether a number means seconds or milliseconds.

const text = JSON.stringify({ at: new Date('2026-01-02T03:04:05Z') });
const restored = JSON.parse(text);
console.log(text);
console.log(typeof restored.at);
const text = JSON.stringify({ at: new Date('2026-01-02T03:04:05Z') });
const restored = JSON.parse(text);
console.log(text);
console.log(typeof restored.at);
const text = JSON.stringify({ at: new Date('2026-01-02T03:04:05Z') });
const restored = JSON.parse(text);
console.log(text);
console.log(typeof restored.at);

JavaScript serializes this Date as an ISO-style UTC string, and parsing the text returns a string, as the output shows. Consumers must deliberately validate and convert it. A calendar date such as a birthday also needs a different contract from an instant: inventing midnight UTC can change the displayed date in another timezone.

26. How can binary data be carried in JSON?

JSON does not have a binary value type. A common contract represents bytes as a Base64 string and identifies the encoding separately. Base64 is an encoding, not encryption, and the receiver must still enforce size limits and validate the decoded content.

const bytes = Buffer.from([0, 255]);
const encoded = bytes.toString('base64');
console.log(encoded);
console.log(Buffer.from(encoded, 'base64').equals(bytes));
const bytes = Buffer.from([0, 255]);
const encoded = bytes.toString('base64');
console.log(encoded);
console.log(Buffer.from(encoded, 'base64').equals(bytes));
const bytes = Buffer.from([0, 255]);
const encoded = bytes.toString('base64');
console.log(encoded);
console.log(Buffer.from(encoded, 'base64').equals(bytes));

The example prints AP8= and true. Two bytes require four Base64 characters here; in general the encoded length is four times the ceiling of the byte length divided by three, before JSON overhead. For large files, a separate binary transfer and a JSON metadata record may be more practical.

27. Why can a large JSON integer lose precision in JavaScript?

JSON’s number grammar does not impose JavaScript’s binary64 representation. However, ordinary JavaScript parsing produces Number values, and integers outside the safe integer range may be rounded. A document can be valid JSON while its numeric value is not preserved exactly by a particular consumer.

console.log(JSON.parse('9007199254740993'));
console.log(JSON.parse('"9007199254740993"'));
console.log(JSON.parse('9007199254740993'));
console.log(JSON.parse('"9007199254740993"'));
console.log(JSON.parse('9007199254740993'));
console.log(JSON.parse('"9007199254740993"'));

The output is 9007199254740992 followed by the unchanged string 9007199254740993. Quoting an identifier is a deliberate type contract, not a repair to apply blindly to all numeric measurements. Decide the representation before parsing; converting an already rounded Number to a string cannot recover its lost digit.

28. Can JSON.stringify serialize a JavaScript BigInt directly?

Ordinary JSON.stringify throws a TypeError for a BigInt unless an explicit customization handles it. JSON has no separate BigInt type marker. Applications commonly transfer a decimal string when exact large integers must survive across languages.

try { JSON.stringify({ id: 9007199254740993n }); }
catch (error) { console.log(error instanceof TypeError); }
console.log(JSON.stringify({ id: String(9007199254740993n) }));
try { JSON.stringify({ id: 9007199254740993n }); }
catch (error) { console.log(error instanceof TypeError); }
console.log(JSON.stringify({ id: String(9007199254740993n) }));
try { JSON.stringify({ id: 9007199254740993n }); }
catch (error) { console.log(error instanceof TypeError); }
console.log(JSON.stringify({ id: String(9007199254740993n) }));

The example prints true and then {"id":"9007199254740993"}. The receiver needs to know that id is a decimal string identifier or an exact integer representation. Do not make every numeric-looking string a BigInt automatically, because postal codes and account identifiers can have meaningful leading zeroes.

29. What changes when JSON is pretty-printed or minified?

Pretty-printing adds permitted whitespace to make structure easier to read. Minification removes unnecessary whitespace outside strings. Neither should change the represented values, but the resulting bytes, length, and text hashes differ.

For example, an indented configuration and its compact equivalent can parse to the same data while producing different signatures if a system signs raw bytes. Use a real parser or serializer rather than removing all spaces with a text replacement: a space inside "New York" is part of the value. Canonicalization requires a defined rule beyond ordinary pretty-printing.

30. Does JSON string escaping make data safe to insert into HTML?

No. JSON escaping makes a string fit JSON syntax; it does not make the value safe in every later output context. After parsing, the original characters are available again. HTML, URLs, SQL, and JavaScript source each have their own rules for safely handling data.

For a user-supplied comment displayed on a page, use a text-rendering API such as textContent rather than interpreting the value as HTML. Embedding JSON directly inside an HTML script element also crosses an HTML parsing boundary, so a generic JSON serializer alone should not be treated as a complete embedding defense. Keep data handling separate from executable or markup contexts.

31. What does the application/json media type communicate?

application/json identifies a representation as JSON. In HTTP, a Content-Type header describes the body being sent, while Accept expresses which response media types a client can accept. Neither header guarantees that the actual bytes are valid or that required fields are present.

A request with Content-Type: application/json and a body containing form syntax such as name=Mira is inconsistent. The server should parse according to its contract and report the problem instead of guessing silently. Some APIs use more specific media types with a +json suffix; follow the API’s documented representation.

32. How should a JSON document become an HTTP request body?

Serialize the application value once, encode the resulting text as UTF-8 for interoperable exchange, and send those bytes with the appropriate media type. HTTP is the transport protocol; JSON describes the body’s data format. A successful HTTP exchange does not prove that the body has the expected schema.

For a body representing an object, serializing the object produces {"name":"Mira"}. Serializing that text again produces a JSON string containing escaped quotes, which is a different top-level value. A local parser check can catch that mistake before any network request is made; the transport and authorization still require their own handling.

33. How does valid JSON syntax differ from valid application data?

Syntax validation asks whether the text follows JSON grammar. Application validation asks whether the parsed value has the required structure and acceptable meaning. An empty object can be syntactically valid but unusable for an API that requires a positive quantity.

For example, {"quantity":"many"} parses successfully but fails an integer requirement. Even an integer of 3 might be invalid if only 2 items remain in stock. Separate parsing, structural validation, and checks against current business state so error messages describe the real problem.

34. What is JSON Schema used for?

JSON Schema describes constraints on JSON instances, such as types, required members, numeric limits, and nested structures. It supports validation and documentation of a shared contract. The dialect matters because keyword behavior and available features depend on the specification version.

A schema declaring an integer quantity of at least 1 can reject both the string "3" and the number 0 without writing those checks repeatedly in each client. A schema cannot by itself prove that an order is authorized or that a referenced product exists in a database. Keep those application checks alongside schema validation, and state the dialect explicitly when distributing a schema.

35. Does listing a field in properties make it required?

No. In JSON Schema 2020-12, properties constrains a named member when it is present. The required keyword separately requires its presence. Null is still a value, so declaring a member required does not automatically permit null or make a missing member equivalent to it.

JSON

{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"name":{"type":"string"},"age":{"type":"integer"}},"required":["name"]}
{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"name":{"type":"string"},"age":{"type":"integer"}},"required":["name"]}
{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"name":{"type":"string"},"age":{"type":"integer"}},"required":["name"]}

This schema accepts {"name":"Mira"}, rejects {}, and rejects {"name":null}. The name property must exist and its value must be a string. A missing optional age is allowed; a present age must be an integer. Validators do not need to insert missing fields to enforce these rules.

36. How does additionalProperties control unexpected object members?

additionalProperties controls members not matched by properties or patternProperties in the same schema object. Setting it to false is useful for a deliberately closed input shape, such as detecting a misspelled field. Leaving it out does not reject extra fields by default.

JSON

{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"name":{"type":"string"}},"required":["name"],"additionalProperties":false}
{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"name":{"type":"string"}},"required":["name"],"additionalProperties":false}
{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"name":{"type":"string"}},"required":["name"],"additionalProperties":false}

This schema accepts {"name":"Mira"} and rejects {"name":"Mira","nmae":"Mira"}. Closing an object also affects evolution: an older consumer may reject a new field that it could otherwise ignore. Decide whether strict input checking or forward-compatible extension is appropriate. Composition with other schemas requires more care than this simple object example.

37. When would you use enum instead of const in JSON Schema?

enum allows one of a listed set of values, whereas const allows exactly one specified value. These constraints compare values rather than coercing a string into a number. They are useful for controlled statuses and explicit version markers.

JSON

{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"version":{"const":1},"status":{"enum":["queued","running","done"]}},"required":["version","status"]}
{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"version":{"const":1},"status":{"enum":["queued","running","done"]}},"required":["version","status"]}
{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"version":{"const":1},"status":{"enum":["queued","running","done"]}},"required":["version","status"]}

This schema accepts {"version":1,"status":"queued"} and rejects a status of "unknown" or a version of "1". The required list is still needed to require both members. An enum can enforce a recognized status label, but it cannot by itself determine whether a transition from the record’s previous status is allowed.

38. How do you validate objects inside a JSON array?

Place an object schema under items to constrain each array element, then define that object’s properties and required members. Array constraints such as minItems describe the collection itself. Constraints at the array level do not automatically apply to fields inside each element.

JSON

{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"array","minItems":1,"items":{"type":"object","properties":{"sku":{"type":"string"},"quantity":{"type":"integer","minimum":1}},"required":["sku","quantity"],"additionalProperties":false}}
{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"array","minItems":1,"items":{"type":"object","properties":{"sku":{"type":"string"},"quantity":{"type":"integer","minimum":1}},"required":["sku","quantity"],"additionalProperties":false}}
{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"array","minItems":1,"items":{"type":"object","properties":{"sku":{"type":"string"},"quantity":{"type":"integer","minimum":1}},"required":["sku","quantity"],"additionalProperties":false}}

This schema accepts [{"sku":"A1","quantity":2}], rejects an empty array, and rejects an element whose quantity is 0 or missing. It does not establish that a SKU exists or that two elements have different SKUs. Those are separate requirements; even uniqueItems compares complete elements rather than one selected property.

39. What makes a JSON API error useful to a client?

A useful error representation separates a stable machine-readable code from a human-readable explanation and identifies relevant input fields when appropriate. The API must document its error contract; JSON itself does not prescribe one universal error shape or HTTP status.

JSON

{"error":{"code":"INVALID_QUANTITY","message":"Quantity must be at least 1.","details":[{"field":"quantity","reason":"below_minimum"}]}}
{"error":{"code":"INVALID_QUANTITY","message":"Quantity must be at least 1.","details":[{"field":"quantity","reason":"below_minimum"}]}}
{"error":{"code":"INVALID_QUANTITY","message":"Quantity must be at least 1.","details":[{"field":"quantity","reason":"below_minimum"}]}}

This illustrative response lets a client associate the problem with quantity without parsing the sentence. Keep codes stable when wording changes, and avoid exposing credentials, internal stack traces, or unnecessary personal data. The corresponding HTTP status and retry behavior must also match the actual failure; a JSON error body alone does not define them.

40. Why is JSON not a database or a complete communication protocol?

JSON is a data representation format. It does not provide storage indexes, transactions, authorization, request routing, delivery guarantees, or a query language. A database or network protocol may use JSON while supplying those capabilities separately.

A JSON order saved to a file does not automatically prevent concurrent writers from overwriting one another. Likewise, putting an operation name in a JSON message does not define authentication or retries. In an interview, identify which layer supplies each behavior: JSON carries values, while the application, transport, and storage system define how those values are used.

JSON Interview Questions and Answers for Intermediate

The intermediate answers connect specifications to practical validation and transformation. Examples expose edge cases rather than relying on permissive defaults.

41. Why should a JSON Schema declare its dialect with $schema?

The dialect determines how a validator interprets the schema’s keywords and vocabularies. Declaring $schema makes that contract explicit instead of relying on a tool’s default, which can differ between environments.

JSON:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "array",
  "prefixItems": [
    {
      "type": "string"
    }
  ],
  "items": false
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "array",
  "prefixItems": [
    {
      "type": "string"
    }
  ],
  "items": false
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "array",
  "prefixItems": [
    {
      "type": "string"
    }
  ],
  "items": false
}

Under Draft 2020-12, this schema allows an empty array or one string and rejects additional elements. The empty array remains valid because no minimum length was specified. A validator that supports only an older draft may not interpret prefixItems as intended.

Check that the validator supports the selected dialect and validate the schema itself before validating instances. The URI identifies the schema language; merely inserting it into a document does not upgrade an old validation library or prove that every vocabulary is implemented.

42. How do $id and $ref affect reference resolution?

$id establishes a schema resource’s identifier and base URI, while $ref identifies a schema to apply. Relative references resolve against the relevant base URI, which can change inside embedded schema resources.

If a schema has $id equal to https://schemas.example.test/orders/order, a reference to ../common/address resolves to https://schemas.example.test/common/address. Moving the schema file on disk does not necessarily change that logical identity.

An identifier is not an instruction to perform an unrestricted network fetch. Applications can register schema resources locally and resolve references through a controlled registry. Keep identifiers stable, detect missing resources before accepting traffic, and distinguish a resolution failure from an instance that simply violates a successfully loaded schema.

43. How does $defs support reusable constraints without automatically applying them?

$defs stores named subschemas for reuse. A definition does not constrain an instance merely because it exists; an applicable reference or other schema structure must use it.

JSON:

{
  "$defs": {
    "code": {
      "type": "string",
      "pattern": "^[A-Z]{2}$"
    }
  },
  "type": "object",
  "properties": {
    "origin": {
      "$ref": "#/$defs/code"
    },
    "destination": {
      "$ref": "#/$defs/code"
    }
  },
  "required": [
    "origin",
    "destination"
  ]
}
{
  "$defs": {
    "code": {
      "type": "string",
      "pattern": "^[A-Z]{2}$"
    }
  },
  "type": "object",
  "properties": {
    "origin": {
      "$ref": "#/$defs/code"
    },
    "destination": {
      "$ref": "#/$defs/code"
    }
  },
  "required": [
    "origin",
    "destination"
  ]
}
{
  "$defs": {
    "code": {
      "type": "string",
      "pattern": "^[A-Z]{2}$"
    }
  },
  "type": "object",
  "properties": {
    "origin": {
      "$ref": "#/$defs/code"
    },
    "destination": {
      "$ref": "#/$defs/code"
    }
  },
  "required": [
    "origin",
    "destination"
  ]
}

Both fields must be two uppercase ASCII letters. Changing the shared definition changes both constraints, so reuse is appropriate only when the fields truly share a contract. The schema still permits other properties because it does not close the object.

For larger schema sets, use stable resource identifiers rather than brittle file-relative assumptions. Also keep examples for each use site: a technically reusable string pattern may become the wrong business rule when one field later allows a different code system.

44. Why is allOf not object-oriented inheritance?

allOf requires an instance to satisfy every subschema independently. It does not merge property declarations into a new class or override conflicting constraints from a base schema.

If one branch requires a number to be at least ten and another requires it to be at most five, no number satisfies the composition. Similarly, a branch using additionalProperties: false can reject fields introduced only in another branch because that keyword uses declarations in its own schema object.

Design composition as an intersection of valid instances. In Draft 2020-12, unevaluatedProperties can help close an object after successful composed schemas evaluate its properties. That is a specific evaluation mechanism, not permission for a later branch to cancel an earlier prohibition. Test composed examples rather than reading branches as inheritance declarations.

45. How do anyOf and oneOf differ when their branches overlap?

anyOf accepts an instance that satisfies at least one branch; oneOf accepts it only when exactly one branch succeeds. Overlapping branches therefore make a practical difference.

JSON:

{
  "oneOf": [
    {
      "type": "integer"
    },
    {
      "type": "number",
      "minimum": 0
    }
  ]
}
{
  "oneOf": [
    {
      "type": "integer"
    },
    {
      "type": "number",
      "minimum": 0
    }
  ]
}
{
  "oneOf": [
    {
      "type": "integer"
    },
    {
      "type": "number",
      "minimum": 0
    }
  ]
}

The value -1 passes only the integer branch, while 1.5 passes only the nonnegative-number branch. The value 1 passes both and is rejected by this oneOf schema. Replacing it with anyOf would accept all three.

For alternative object shapes, a required discriminator with a different const in each branch can make the alternatives intentionally exclusive. Do not select oneOf just because the API documentation says “one of these examples”; first decide whether overlap should be an error.

46. How do if, then and else express a conditional document rule?

if selects which constraint branch applies; it does not by itself require the instance to match the condition. A successful condition applies then, while a failed condition applies else when present.

JSON:

{
  "type": "object",
  "properties": {
    "kind": {
      "enum": [
        "delivery",
        "pickup"
      ]
    }
  },
  "required": [
    "kind"
  ],
  "if": {
    "properties": {
      "kind": {
        "const": "delivery"
      }
    },
    "required": [
      "kind"
    ]
  },
  "then": {
    "required": [
      "address"
    ]
  },
  "else": {
    "required": [
      "pickupPoint"
    ]
  }
}
{
  "type": "object",
  "properties": {
    "kind": {
      "enum": [
        "delivery",
        "pickup"
      ]
    }
  },
  "required": [
    "kind"
  ],
  "if": {
    "properties": {
      "kind": {
        "const": "delivery"
      }
    },
    "required": [
      "kind"
    ]
  },
  "then": {
    "required": [
      "address"
    ]
  },
  "else": {
    "required": [
      "pickupPoint"
    ]
  }
}
{
  "type": "object",
  "properties": {
    "kind": {
      "enum": [
        "delivery",
        "pickup"
      ]
    }
  },
  "required": [
    "kind"
  ],
  "if": {
    "properties": {
      "kind": {
        "const": "delivery"
      }
    },
    "required": [
      "kind"
    ]
  },
  "then": {
    "required": [
      "address"
    ]
  },
  "else": {
    "required": [
      "pickupPoint"
    ]
  }
}

A delivery needs an address, while a pickup needs a pickup point. The explicit required check in the condition prevents a missing discriminator from accidentally satisfying a condition that only describes properties when present.

Add field-type and content constraints separately; required checks presence, not whether an address is a nonempty valid address. Test the missing discriminator, unknown value and both branches, because a conditional schema can be logically correct while leaving important values unconstrained.

47. When should you use dependentRequired instead of dependentSchemas?

dependentRequired expresses a presence dependency: when one property exists, specified other properties must also exist. dependentSchemas applies a complete subschema to the whole object when the triggering property exists.

JSON:

{
  "type": "object",
  "dependentRequired": {
    "cardNumber": [
      "billingAddress"
    ]
  },
  "dependentSchemas": {
    "companyId": {
      "required": [
        "accountType"
      ],
      "properties": {
        "accountType": {
          "const": "business"
        }
      }
    }
  }
}
{
  "type": "object",
  "dependentRequired": {
    "cardNumber": [
      "billingAddress"
    ]
  },
  "dependentSchemas": {
    "companyId": {
      "required": [
        "accountType"
      ],
      "properties": {
        "accountType": {
          "const": "business"
        }
      }
    }
  }
}
{
  "type": "object",
  "dependentRequired": {
    "cardNumber": [
      "billingAddress"
    ]
  },
  "dependentSchemas": {
    "companyId": {
      "required": [
        "accountType"
      ],
      "properties": {
        "accountType": {
          "const": "business"
        }
      }
    }
  }
}

A card number requires a billing address. A company ID activates both a presence requirement and a value constraint on the account type. Neither dependency runs in reverse unless that reverse rule is separately declared.

Presence includes a property whose value is null, so use ordinary type constraints if null should not count as a meaningful supplied value. These keywords do not compare two property values; a rule such as matching two entered passwords generally needs an application-level comparison or an explicitly supported extension.

48. How does unevaluatedProperties differ from additionalProperties?

additionalProperties deals with properties not covered by properties or patternProperties in the same schema object. unevaluatedProperties can account for properties evaluated through applicable successful subschemas, making it useful with composition.

JSON:

{
  "type": "object",
  "allOf": [
    {
      "properties": {
        "name": {
          "type": "string"
        }
      }
    },
    {
      "properties": {
        "age": {
          "type": "integer"
        }
      }
    }
  ],
  "unevaluatedProperties": false
}
{
  "type": "object",
  "allOf": [
    {
      "properties": {
        "name": {
          "type": "string"
        }
      }
    },
    {
      "properties": {
        "age": {
          "type": "integer"
        }
      }
    }
  ],
  "unevaluatedProperties": false
}
{
  "type": "object",
  "allOf": [
    {
      "properties": {
        "name": {
          "type": "string"
        }
      }
    },
    {
      "properties": {
        "age": {
          "type": "integer"
        }
      }
    }
  ],
  "unevaluatedProperties": false
}

This permits the evaluated name and age fields and rejects an extra nickname. It does not require either permitted property because no required array is present.

Evaluation across alternatives and references follows dialect rules; it is not a textual scan of every property name anywhere in the schema. Use a validator with Draft 2020-12 support and test failed branches as well as successful ones. Closing an object can also make future additive fields a compatibility concern.

49. How do prefixItems and items describe tuple-like arrays in Draft 2020-12?

prefixItems applies schemas by position to an initial array prefix. items controls subsequent elements in that dialect; minimum and maximum lengths remain separate constraints.

JSON:

{
  "type": "array",
  "prefixItems": [
    {
      "type": "string"
    },
    {
      "type": "integer",
      "minimum": 0
    }
  ],
  "items": false,
  "minItems": 2
}
{
  "type": "array",
  "prefixItems": [
    {
      "type": "string"
    },
    {
      "type": "integer",
      "minimum": 0
    }
  ],
  "items": false,
  "minItems": 2
}
{
  "type": "array",
  "prefixItems": [
    {
      "type": "string"
    },
    {
      "type": "integer",
      "minimum": 0
    }
  ],
  "items": false,
  "minItems": 2
}

The intended pair is a name followed by a nonnegative integer, such as ["Ada", 3]. The minimum length requires both positions, and items: false rejects a third element. Without the minimum, a shorter array could pass.

Use an object with named fields when positional meaning would make the API fragile. If a tuple is appropriate, document the order and avoid importing older-draft array syntax unchanged. Draft 2020-12’s division between prefix and remaining items differs from earlier tuple conventions.

50. How do contains, minContains and maxContains constrain matching array elements?

contains describes a condition that array elements must satisfy in the required count. With it, minContains and maxContains set the allowed number of matching elements; they do not limit the array’s total length.

JSON:

{
  "type": "array",
  "contains": {
    "type": "integer",
    "minimum": 10
  },
  "minContains": 1,
  "maxContains": 2
}
{
  "type": "array",
  "contains": {
    "type": "integer",
    "minimum": 10
  },
  "minContains": 1,
  "maxContains": 2
}
{
  "type": "array",
  "contains": {
    "type": "integer",
    "minimum": 10
  },
  "minContains": 1,
  "maxContains": 2
}

The array [1, 10, 12] has two matches and passes, while [10, 11, 12] has three and fails. Unmatched elements remain permitted unless another keyword constrains them.

Use items when every element must satisfy a rule and contains when a subset must exist. For example, a list may require every entry to be an object while requiring at least one entry with a particular role. Counting matches is different from requiring all role names to be unique.

51. What does uniqueItems compare in arrays of objects?

uniqueItems: true requires array items to be distinct JSON values. It does not select an identifier field and enforce uniqueness on just that field.

Two objects with the same key-value content are duplicates even if their member order differs. But {"id": 1, "name": "A"} and {"id": 1, "name": "B"} are different values, so whole-item uniqueness alone does not reject their repeated ID.

If business identity must be unique, validate that rule in the application or choose a representation that expresses it naturally, such as an object keyed by a validated identifier where suitable. Also remember that JSON numeric equality is mathematical for schema purposes: writing an equal number with a different textual form does not create a distinct item.

52. Why can multipleOf reveal numeric precision differences between validators?

multipleOf expresses a mathematical divisibility condition for JSON numbers, but libraries often represent numbers using binary floating point. A validator’s numeric implementation can therefore affect boundary cases involving decimal fractions.

A schema with multipleOf: 0.01 intends to allow hundredth increments, including 0.29. If either schema values or instance values were converted to inexact binary numbers, a naive remainder test could disagree with that intent. Test the actual validator and parsing configuration instead of writing a homemade float-modulo validator.

For money, an integer minor-unit contract can simplify exact validation, provided the currency scale is explicit. Decimal-aware parsing and validation are another option, but the schema and instance representations must be compatible. A string pattern for two decimal places checks a representation, not the same mathematical constraint.

53. Does JSON Schema string length count bytes or visible characters?

String length constraints count Unicode code points, not UTF-8 bytes or user-perceived grapheme clusters. A visible character can consist of several code points, so a schema length limit is not automatically a user-interface character count.

The precomposed character é is one code point, while an e followed by a combining acute accent uses two. They can look equivalent while interacting differently with maxLength: 1. Emoji sequences introduce similar issues involving multiple code points.

If the application normalizes Unicode, specify when that happens relative to validation and storage. Do not silently normalize identifiers that require exact preservation. For a user-facing character limit, use an appropriate grapheme-aware rule in addition to clearly documenting what the schema itself enforces.

54. Why should a whole-string JSON Schema pattern usually be anchored?

The pattern keyword asks whether the regular expression matches within the string; it does not implicitly require the match to consume the entire string. Anchors are needed when the contract requires a complete format.

JSON:

{
  "type": "string",
  "pattern": "^[A-Z]{2}[0-9]{3}$",
  "maxLength": 5
}
{
  "type": "string",
  "pattern": "^[A-Z]{2}[0-9]{3}$",
  "maxLength": 5
}
{
  "type": "string",
  "pattern": "^[A-Z]{2}[0-9]{3}$",
  "maxLength": 5
}

This accepts AB123 and rejects a prefix, suffix or terminal newline. The pattern fixes the five ASCII characters; maxLength also closes a portability gap: Python’s regular-expression engine can match $ before a final newline, while JavaScript without multiline mode requires the end here. Test the actual validator rather than assuming identical engine behavior. The length constraint avoids a Python-only anchor in the schema.

Use a portable regex subset supported by the chosen validators and test relevant Unicode and newline cases. Regular expressions are useful for lexical shape, but they are not automatically suitable for complex semantic validation such as verifying that a calendar date actually exists.

55. Does the format keyword always reject an invalid email or date?

No. In Draft 2020-12, format annotation and format assertion are separate vocabularies, and ordinary format support should not be assumed to enforce validity. Behavior depends on the dialect, validator and enabled checking configuration.

A schema declaring format: "email" can document the intended meaning without causing a default validator invocation to reject every malformed address. Check the actual library setup, including optional dependencies and which formats it implements.

Even an asserted email format does not prove deliverability or ownership, and a date-time format does not validate a business deadline. Keep lexical validation, semantic rules and external verification separate. Include a known-invalid fixture in startup or test checks so disabled format enforcement is visible rather than inferred from a successful valid example.

56. Do readOnly and writeOnly automatically prevent fields from crossing an API boundary?

They are schema annotations describing intended usage, not a general-purpose authorization or redaction mechanism. An application or surrounding specification can assign request and response behavior to them, but a basic schema validation pass does not automatically remove or protect values.

A generated identifier marked read-only should normally be controlled by the server’s write path. A password marked write-only should be excluded by the response serializer and never returned merely because the response object happens to contain it.

Test the actual request handling, response serialization and API tooling. An annotation can inform documentation and code generation while still requiring enforcement elsewhere. Access-control decisions should not depend on trusting a client to respect the annotation or on assuming every downstream tool interprets it identically.

57. Does a JSON Schema default insert a missing property?

The standard default keyword is an annotation; validation does not inherently mutate the instance to fill missing fields. Some libraries offer nonstandard default application, which must be treated as a separate behavior.

For a property with a default page size of twenty, the input {} remains an empty object under ordinary validation. If page size is also required, the missing property can still make that instance invalid despite the documented default.

Decide whether defaults are applied before validation, afterward or inside business logic, and test that order. Avoid sharing mutable default arrays or objects between requests in application code. A default should also be sensible for the schema, but its presence alone is not evidence that a validator checked or inserted it.

58. How do you assess whether a schema change is backward compatible?

Specify which side changes and which old data or clients must remain accepted. Compatibility is directional: making a field required narrows valid requests, while allowing a new response field may still break a client that rejects unknown properties.

Changing an optional field to required can reject older senders. Adding a new enum value accepts more input but may surprise an older reader with exhaustive handling. Changing a number to a string can be syntactically valid JSON on both sides while breaking the agreed data contract.

Run representative old and new instances against both contracts and exercise consumers, not only validators. Versioning a schema URI identifies a contract but does not implement migration. Document the rollout order and how mixed versions coexist until older producers and consumers are retired.

59. How do JSON Pointer escapes identify keys containing slashes or tildes?

Within a JSON Pointer token, ~1 represents a slash and ~0 represents a tilde. These escapes distinguish characters inside a key from the slash that separates path segments.

For an object with the key a/b containing the key ~name, the pointer is /a~1b/~0name. Decode ~1 before ~0 so a token such as ~01 correctly denotes the literal text ~1, not a slash.

The empty pointer addresses the whole document, whereas / addresses an object member with an empty name. A URI-fragment representation adds percent-encoding rules on top of pointer escaping; do not apply URL decoding and pointer decoding interchangeably.

60. How does JSON Pointer interpret array indices and the dash token?

For an array, a pointer token selects a zero-based element using the specified integer syntax. Leading-zero forms such as 01 are not valid array indices under JSON Pointer, although an object can have a literal key with that name.

The pointer /items/0 selects the first array member. The dash token denotes the nonexistent position after the last element; ordinary pointer resolution cannot retrieve a value from it. JSON Patch gives that token useful append behavior specifically for an add operation.

Interpret the token in the context of the current value’s type. A numeric-looking key on an object is still a key, and traversing through a scalar fails. Applications should report a missing or invalid path distinctly from a target value that legitimately exists and is null.

61. Why must JSON Patch operations be evaluated in sequence?

Each JSON Patch operation applies to the document produced by preceding operations. Paths can therefore refer to values added earlier, and array indices can change after removals or insertions.

JSON:

[
  {
    "op": "remove",
    "path": "/items/0"
  },
  {
    "op": "replace",
    "path": "/items/0",
    "value": "Z"
  }
]
[
  {
    "op": "remove",
    "path": "/items/0"
  },
  {
    "op": "replace",
    "path": "/items/0",
    "value": "Z"
  }
]
[
  {
    "op": "remove",
    "path": "/items/0"
  },
  {
    "op": "replace",
    "path": "/items/0",
    "value": "Z"
  }
]

Starting with items A, B and C, removal leaves B and C; replacement then changes B to Z. Interpreting both paths against the original array would produce the wrong result. If an operation fails, evaluation stops and the patch is unsuccessful.

When used with HTTP PATCH, the server must apply the patch atomically so a failed operation does not expose a partially modified resource. An in-memory patch library may mutate its input before reporting failure, so the service must implement the required transaction or copy-and-commit boundary rather than assuming a library exception undoes earlier mutations.

62. How can a JSON Patch test operation detect a stale edit?

Place a test operation on the expected version or relevant prior value before the modifying operations. If the condition is not satisfied, the patch fails instead of silently applying an edit based on stale state.

JSON:

[
  {
    "op": "test",
    "path": "/version",
    "value": 3
  },
  {
    "op": "replace",
    "path": "/title",
    "value": "Reviewed"
  },
  {
    "op": "replace",
    "path": "/version",
    "value": 4
  }
]
[
  {
    "op": "test",
    "path": "/version",
    "value": 3
  },
  {
    "op": "replace",
    "path": "/title",
    "value": "Reviewed"
  },
  {
    "op": "replace",
    "path": "/version",
    "value": 4
  }
]
[
  {
    "op": "test",
    "path": "/version",
    "value": 3
  },
  {
    "op": "replace",
    "path": "/title",
    "value": "Reviewed"
  },
  {
    "op": "replace",
    "path": "/version",
    "value": 4
  }
]

This patch expects version three and advances it to four as part of the same update. The service must evaluate the test and changes against one protected resource state; a separate read followed by an unprotected write would leave a race.

The test is not an authorization check. Enforce which paths the caller may change and consider HTTP conditional requests such as an appropriate If-Match contract. Report a conflict in a way that lets the client refresh or reconcile, rather than automatically retrying the stale values.

63. How do add, replace and remove differ for objects and arrays?

replace and remove require an existing target. add can create an object member, replace an existing object member or insert into an array at the specified position, provided the required parent exists.

Adding X at array index one to A, B produces A, X, B; replacing index one produces A, X. Adding at the dash position appends. An index beyond the allowed insertion position is not a request to fill the gap with nulls.

Validate operation-specific requirements and distinguish missing parents from a missing final object member. If the resource schema prohibits a field or the caller cannot edit it, the patch’s syntactic validity does not override those rules. Validate the resulting resource and apply the endpoint’s atomicity contract.

64. What is the difference between JSON Patch move and copy?

copy reads a value from its source path and adds that value at the destination, while move removes the source and adds it at the destination. A copied JSON value does not establish a live shared-reference relationship between the two locations.

Moving array index zero to index two in A, B, C yields B, C, A: removal happens before the destination insertion. This order matters when source and destination are in the same array. The source must exist, and a move cannot place a value inside one of its own descendants.

Both operations still need destination and authorization checks. Copying a sensitive property into a public field can violate policy even if both paths exist. Evaluate the effect of the whole patch, not merely whether the operation names appear on an allowlist.

65. Why does null have special meaning in JSON Merge Patch?

In an object merge patch, a member whose patch value is null requests removal of that member from the target object. It does not assign a stored JSON null at that member.

JSON:

{
  "nickname": null,
  "city": "Pune"
}
{
  "nickname": null,
  "city": "Pune"
}
{
  "nickname": null,
  "city": "Pune"
}

Applied to an object with a nickname and city, this removes the nickname and sets the city to Pune while preserving unrelated members. An absent member in the patch leaves the corresponding target member alone.

This makes Merge Patch convenient for many partial object updates but awkward when explicit null is an important stored value. Select another update contract when callers must distinguish set-to-null from remove. Also note that a non-object patch, including a top-level null, replaces the entire target rather than performing member-by-member merging.

66. How does JSON Merge Patch update an array?

An array supplied by a merge patch replaces the target value as a whole. Merge Patch does not match array elements by ID or recursively merge corresponding positions.

If the target has tags A and B, a patch containing tags B produces only B. It is not an instruction to add B or remove A by identity. Similarly, patching an array of objects requires sending the desired replacement array, including any entries that should remain.

Whole-array replacement can overwrite a concurrent edit unless the endpoint has a concurrency contract. JSON Patch can express element-level operations, but positional paths still need careful handling when other writers modify the array. Choose the patch format based on the resource’s meaning and update behavior, not on which payload is shorter in one example.

67. How can a JavaScript replacer and reviver implement an explicit serialization contract?

A stringify replacer controls values included in serialized output; a parse reviver transforms parsed values. They operate on opposite sides of the conversion and should follow a narrow documented contract rather than guess types from every string.

const assert = require("node:assert/strict");
const text = JSON.stringify({name: "Ada", token: "secret"},
  (key, value) => key === "token" ? undefined : value);
assert.equal(text, '{"name":"Ada"}');
const record = JSON.parse('{"createdAt":"2026-01-02T00:00:00Z"}',
  (key, value) => key === "createdAt" ? new Date(value) : value);
assert.equal(record.createdAt.toISOString(), "2026-01-02T00:00:00.000Z");
const assert = require("node:assert/strict");
const text = JSON.stringify({name: "Ada", token: "secret"},
  (key, value) => key === "token" ? undefined : value);
assert.equal(text, '{"name":"Ada"}');
const record = JSON.parse('{"createdAt":"2026-01-02T00:00:00Z"}',
  (key, value) => key === "createdAt" ? new Date(value) : value);
assert.equal(record.createdAt.toISOString(), "2026-01-02T00:00:00.000Z");
const assert = require("node:assert/strict");
const text = JSON.stringify({name: "Ada", token: "secret"},
  (key, value) => key === "token" ? undefined : value);
assert.equal(text, '{"name":"Ada"}');
const record = JSON.parse('{"createdAt":"2026-01-02T00:00:00Z"}',
  (key, value) => key === "createdAt" ? new Date(value) : value);
assert.equal(record.createdAt.toISOString(), "2026-01-02T00:00:00.000Z");

The example omits the token and revives only the explicitly named timestamp field. Validate the date string before relying on it in a real contract; converting every date-looking string can unexpectedly change identifiers or user text.

A reviver returning undefined deletes the corresponding property, so a missing return can destroy data. A replacer is also not a complete security boundary: build response objects deliberately, and account for arrays, custom serialization and nested fields.

68. How can toJSON change the output of JSON.stringify?

When an object supplies an applicable toJSON method, stringify uses its returned representation. This means serialization can differ from the object’s ordinary enumerable properties and can execute custom application code.

const assert = require("node:assert/strict");
const account = {
  id: 7,
  internalNote: "review",
  toJSON() { return {id: this.id}; }
};
assert.equal(JSON.stringify(account), '{"id":7}');
assert.equal(account.internalNote, "review");
const assert = require("node:assert/strict");
const account = {
  id: 7,
  internalNote: "review",
  toJSON() { return {id: this.id}; }
};
assert.equal(JSON.stringify(account), '{"id":7}');
assert.equal(account.internalNote, "review");
const assert = require("node:assert/strict");
const account = {
  id: 7,
  internalNote: "review",
  toJSON() { return {id: this.id}; }
};
assert.equal(JSON.stringify(account), '{"id":7}');
assert.equal(account.internalNote, "review");

The note remains on the original object but is absent from this serialized representation. Date objects similarly have defined serialization behavior, so a parsed date string does not automatically round-trip to the same runtime object type.

Inspect custom serialization when debugging a mismatch between logged objects and wire payloads. Keep side effects out of serialization where possible and test the representation contract. A method that hides one property does not prove that every alternative export or logging path protects it.

69. How does JavaScript serialize undefined and nonfinite numeric values?

Stringify omits an object property whose value is undefined, while an undefined array element becomes null. Nonfinite numbers such as NaN and Infinity become null, so serialization can silently lose distinctions present in the runtime value.

const assert = require("node:assert/strict");
assert.equal(JSON.stringify({a: undefined, b: NaN}), '{"b":null}');
assert.equal(JSON.stringify([undefined, Infinity]), '[null,null]');
assert.equal(JSON.stringify(undefined), undefined);
const assert = require("node:assert/strict");
assert.equal(JSON.stringify({a: undefined, b: NaN}), '{"b":null}');
assert.equal(JSON.stringify([undefined, Infinity]), '[null,null]');
assert.equal(JSON.stringify(undefined), undefined);
const assert = require("node:assert/strict");
assert.equal(JSON.stringify({a: undefined, b: NaN}), '{"b":null}');
assert.equal(JSON.stringify([undefined, Infinity]), '[null,null]');
assert.equal(JSON.stringify(undefined), undefined);

The last result is the JavaScript value undefined, not a JSON text containing that word. An API expecting a string must handle that top-level case explicitly.

Validate values before serialization if null would misrepresent missing or invalid data. Define whether nonfinite calculations should fail, become a tagged error or be represented by another agreed form. Do not assume a successful stringify call proves that the original data can be reconstructed exactly.

70. How do you make Python reject nonstandard NaN and Infinity JSON values?

For output, use allow_nan=False so nonfinite floats cause an error instead of emitting nonstandard numeric tokens. For input, supply a rejecting parse_constant function because the standard library otherwise accepts those extensions.

import json

try:
    json.dumps({"value": float("nan")}, allow_nan=False)
except ValueError:
    pass
else:
    raise AssertionError("Expected nonfinite output to fail")

def reject_constant(value):
    raise ValueError(f"Invalid JSON constant: {value}")

try:
    json.loads('{"value": Infinity}', parse_constant=reject_constant)
except ValueError:
    pass
else:
    raise AssertionError("Expected nonstandard input to fail")
import json

try:
    json.dumps({"value": float("nan")}, allow_nan=False)
except ValueError:
    pass
else:
    raise AssertionError("Expected nonfinite output to fail")

def reject_constant(value):
    raise ValueError(f"Invalid JSON constant: {value}")

try:
    json.loads('{"value": Infinity}', parse_constant=reject_constant)
except ValueError:
    pass
else:
    raise AssertionError("Expected nonstandard input to fail")
import json

try:
    json.dumps({"value": float("nan")}, allow_nan=False)
except ValueError:
    pass
else:
    raise AssertionError("Expected nonfinite output to fail")

def reject_constant(value):
    raise ValueError(f"Invalid JSON constant: {value}")

try:
    json.loads('{"value": Infinity}', parse_constant=reject_constant)
except ValueError:
    pass
else:
    raise AssertionError("Expected nonstandard input to fail")

These settings address nonfinite-number extensions, not every possible application constraint. Duplicate keys, integer ranges, document size and schema validation remain separate decisions.

Normalize or reject invalid analytical results deliberately before export. Replacing every nonfinite value with zero may satisfy a parser while materially changing the meaning of the data.

71. How can Python detect duplicate object names while parsing JSON?

Use object_pairs_hook to inspect ordered name-value pairs before they become an ordinary dictionary. Once duplicate names have been collapsed into one mapping entry, the evidence needed to reject them may be lost.

import json

def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"Duplicate key: {key}")
        result[key] = value
    return result

try:
    json.loads('{"role":"reader","role":"admin"}',
               object_pairs_hook=unique_object)
except ValueError:
    pass
else:
    raise AssertionError("Expected duplicate key rejection")
import json

def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"Duplicate key: {key}")
        result[key] = value
    return result

try:
    json.loads('{"role":"reader","role":"admin"}',
               object_pairs_hook=unique_object)
except ValueError:
    pass
else:
    raise AssertionError("Expected duplicate key rejection")
import json

def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"Duplicate key: {key}")
        result[key] = value
    return result

try:
    json.loads('{"role":"reader","role":"admin"}',
               object_pairs_hook=unique_object)
except ValueError:
    pass
else:
    raise AssertionError("Expected duplicate key rejection")

The hook also applies to nested objects. It rejects duplicates explicitly instead of depending on a particular consumer’s first-value or last-value behavior.

Apply the same policy across the processing chain. A security check and a downstream consumer that interpret duplicates differently can disagree about the effective value. This hook validates object-name uniqueness; it does not replace schema checks or limits on input size and nesting.

72. What does parse_float=Decimal preserve, and what does it not solve?

It parses JSON fractional or exponent-form numbers into Decimal values directly from their text, avoiding an initial binary-float approximation. It does not automatically provide Decimal serialization or decide arithmetic precision and rounding policy.

import json
from decimal import Decimal

value = json.loads('{"amount": 0.10}', parse_float=Decimal)
assert value["amount"] == Decimal("0.10")
assert str(value["amount"]) == "0.10"
try:
    json.dumps(value)
except TypeError:
    pass
else:
    raise AssertionError("Standard encoder does not encode Decimal")
import json
from decimal import Decimal

value = json.loads('{"amount": 0.10}', parse_float=Decimal)
assert value["amount"] == Decimal("0.10")
assert str(value["amount"]) == "0.10"
try:
    json.dumps(value)
except TypeError:
    pass
else:
    raise AssertionError("Standard encoder does not encode Decimal")
import json
from decimal import Decimal

value = json.loads('{"amount": 0.10}', parse_float=Decimal)
assert value["amount"] == Decimal("0.10")
assert str(value["amount"]) == "0.10"
try:
    json.dumps(value)
except TypeError:
    pass
else:
    raise AssertionError("Standard encoder does not encode Decimal")

Converting the Decimal to a string creates a JSON string, which changes the wire type. Converting it to float can lose the precision the parser preserved. Choose an encoder and contract that intentionally support the desired numeric representation.

Integers use a separate parsing path, and Decimal arithmetic still follows its configured context. Test large numbers, exponent notation and downstream consumers rather than treating one exact decimal parse as an end-to-end precision guarantee.

73. What does NDJSON framing require from producers and consumers?

NDJSON places one complete JSON text on each line, allowing records to be processed without collecting one giant array. Producers must keep each record on one line, and consumers need an explicit policy for malformed and empty lines.

import json

records = [{"id": 1, "note": "first\nsecond"}, {"id": 2}]
text = "\n".join(json.dumps(x, allow_nan=False) for x in records) + "\n"
parsed = [json.loads(line) for line in text.splitlines()]
assert parsed == records
assert len(text.splitlines()) == 2
import json

records = [{"id": 1, "note": "first\nsecond"}, {"id": 2}]
text = "\n".join(json.dumps(x, allow_nan=False) for x in records) + "\n"
parsed = [json.loads(line) for line in text.splitlines()]
assert parsed == records
assert len(text.splitlines()) == 2
import json

records = [{"id": 1, "note": "first\nsecond"}, {"id": 2}]
text = "\n".join(json.dumps(x, allow_nan=False) for x in records) + "\n"
parsed = [json.loads(line) for line in text.splitlines()]
assert parsed == records
assert len(text.splitlines()) == 2

The newline inside the note is escaped within the JSON string, so it does not create another record boundary. Pretty-printing a record across several physical lines would break this framing contract.

A transport chunk is not necessarily a line. Buffer incomplete records and enforce a maximum record size. Decide whether an invalid record stops the stream or is quarantined with a line reference; silently skipping it can hide data loss.

74. How do RFC 7464 JSON text sequences differ from newline-delimited JSON?

RFC 7464 defines UTF-8 JSON text sequences using the ASCII record separator byte, hexadecimal 1E, before each JSON text and a line feed after it. Its media type is application/json-seq; it is a distinct framing format from NDJSON.

The explicit record separator allows a parser to locate the next candidate record after malformed or truncated input according to the sequence-processing rules. A line feed inside a pretty-printed object is not itself the record separator, which differs from a one-record-per-line convention.

Use a parser that understands the selected format and define how malformed records are reported. Searching for braces or treating every newline as a boundary is not an implementation of the RFC. Keep transport framing separate from whether each recovered record satisfies its application schema.

75. Why cannot an incremental JSON parser treat every network chunk as a complete document?

Transport chunks can split any part of the representation, including a UTF-8 character, an escaped string or a numeric token. Chunk boundaries reflect transport behavior, not the JSON grammar.

A receiver may obtain the bytes for a string in several reads, with the backslash and its escaped character in different chunks. It needs incremental text decoding and parser state that survives those boundaries. Appending a closing brace or retrying each chunk as an independent document would invent or lose data.

Use a real incremental parser or a documented framed-record approach with bounded buffering. Test one-byte chunks, split multibyte characters, truncated final input and oversized records. A parser that accepts partial input must still signal when the stream ends before the current value is complete.

76. How would you process a very large JSON array with bounded memory?

Use an event-based or incremental parser that yields array elements as they are completed, and process each element without retaining the entire collection. Loading the file with an ordinary whole-document parser defeats that memory goal.

For an array of records, validate and write each record to a bounded staging workflow, while preserving its index for errors. Streaming the outer array does not bound the size of one enormous element, so impose per-element size or complexity limits as well.

Decide what happens if a later element is invalid. Earlier external effects may already have occurred, requiring staging, checkpoints or reconciliation rather than assuming all-or-nothing behavior. Also preserve backpressure so a fast parser does not simply move the unbounded buffer into a downstream queue.

77. Why must an HTTP PATCH endpoint distinguish patch media types?

The HTTP method identifies partial modification, while the request media type identifies how to interpret the patch document. JSON Patch and JSON Merge Patch have different semantics and use application/json-patch+json and application/merge-patch+json, respectively.

An array of operations is meaningful under JSON Patch, while an object containing null members has deletion semantics under Merge Patch. Accepting both as generic application/json without a documented interpretation can make identical-looking values mean different actions.

Validate the declared supported format, authorization and resulting resource, and apply the required atomic update behavior. An endpoint can advertise supported patch formats through Accept-Patch. Media-type selection does not eliminate concurrency control, so combine it with the resource’s conditional-request policy where needed.

78. What should a paginated JSON response make explicit?

Define the record array, continuation state and ordering contract, including how the final page is represented. Consumers should not have to infer whether a missing field, null cursor or empty array means the same thing.

JSON:

{
  "items": [
    {
      "id": "a7"
    },
    {
      "id": "b2"
    }
  ],
  "nextCursor": "opaque-token"
}
{
  "items": [
    {
      "id": "a7"
    },
    {
      "id": "b2"
    }
  ],
  "nextCursor": "opaque-token"
}
{
  "items": [
    {
      "id": "a7"
    },
    {
      "id": "b2"
    }
  ],
  "nextCursor": "opaque-token"
}

This shape can use a null next cursor for completion if the contract says so. The cursor should be treated as opaque by the client, and requests using it should preserve the filters and ordering it represents. An empty page does not necessarily prove completion unless the protocol guarantees it.

Distinguish exact totals from estimates and explain whether pages represent a snapshot or a changing dataset. Validate cursor expiry and tampering on the server. A well-formed JSON response does not by itself prevent duplicate or skipped records when the underlying data changes.

79. How should a validation error identify a deeply nested failing value?

Return a machine-readable instance path, a stable error category and a useful explanation, with schema-location information when appropriate. Keep the path to the data distinct from the path to the rule that failed.

For an invalid quantity in the third order line, /orders/2/quantity identifies the instance location using JSON Pointer. A schema path points instead to the applicable minimum or type constraint. Escaping property names correctly matters when names contain slashes or tildes.

Handle missing-property errors carefully: there may be no existing value at the desired child path, so include the missing property separately. Avoid returning full sensitive values in diagnostics, and do not force clients to parse human prose to determine which form field needs attention.

80. How does OpenAPI 3.1 align with JSON Schema without making every object a schema?

OpenAPI 3.1 aligns its Schema Object with JSON Schema Draft 2020-12 through an OpenAPI-specific dialect. This expands compatibility, but an OpenAPI document also contains operation, parameter and other objects with their own rules; not every object in the document is a JSON Schema.

When migrating a 3.0 schema, represent nullable values using JSON Schema’s type alternatives, such as type: ["string", "null"], rather than assuming the older nullable convention remains the same validation keyword. Check the declared dialect and the tooling’s actual OpenAPI and JSON Schema support.

Test generated clients, request validation and response validation together. A tool that parses the OpenAPI document can still implement only part of the schema dialect. Pin the OpenAPI version and schema dialect used by the contract so a tooling upgrade can be checked against the same examples.

JSON Interview Questions and Answers for Experienced

Experienced answers examine failure modes that appear between components. They distinguish byte-level representation, parsed values and business meaning before defining validation or recovery behavior.

81. How can escaped object names bypass a raw-text duplicate-key check?

Detect duplicate names after decoding JSON string escapes, before collapsing member pairs into a mapping. Different source spellings can denote the same property; scanning the original bytes for repeated quoted text misses that equivalence.

import json

def unique_members(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("duplicate member: " + key)
        result[key] = value
    return result

payload = r'{"role":"reader","\u0072ole":"owner"}'
try:
    json.loads(payload, object_pairs_hook=unique_members)
except ValueError as error:
    assert str(error) == "duplicate member: role"
else:
    raise AssertionError("escaped duplicate was accepted")
import json

def unique_members(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("duplicate member: " + key)
        result[key] = value
    return result

payload = r'{"role":"reader","\u0072ole":"owner"}'
try:
    json.loads(payload, object_pairs_hook=unique_members)
except ValueError as error:
    assert str(error) == "duplicate member: role"
else:
    raise AssertionError("escaped duplicate was accepted")
import json

def unique_members(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("duplicate member: " + key)
        result[key] = value
    return result

payload = r'{"role":"reader","\u0072ole":"owner"}'
try:
    json.loads(payload, object_pairs_hook=unique_members)
except ValueError as error:
    assert str(error) == "duplicate member: role"
else:
    raise AssertionError("escaped duplicate was accepted")

Both names decode to role, so the hook rejects the payload. Run this check on every nested object and pass the resulting validated representation onward; a later reparse with a different policy can recreate the disagreement.

Escape decoding is not Unicode normalization or case folding. Visually similar names, or Role and role, are distinct JSON names unless the application defines additional identity rules. If it does, validate collisions under those rules separately before authorization or storage.

82. What does RFC 8785 canonicalization provide beyond sorting object keys?

JCS defines a complete canonical representation for its supported JSON data model, including primitive serialization, recursive property ordering and UTF-8 output. It is intended to make hashing and signing reproducible for equivalent supported inputs.

A generic serializer with sorted keys is not automatically JCS compliant. Number formatting, escaping and the UTF-16 code-unit ordering of property names must follow the specified rules; ordinary language-specific string sorting can differ.

Use a conforming implementation and published test vectors when the protocol requires JCS. Keep array order intact and reject unsupported inputs rather than inventing a local canonical form. RFC 8785 is an Informational specification; the application must explicitly choose it as part of its protocol.

83. When should a signature cover original JSON bytes versus canonical JSON?

The protocol must choose what is authenticated. Signing original bytes authenticates one exact representation, while signing a defined canonical representation can allow specified formatting differences without invalidating the signature.

The documents with different whitespace or object-member order may parse to the same application value but have different byte hashes. Conversely, parsing and reserializing before verifying an exact-byte signature can destroy the representation that was actually signed.

Signed representation

Formatting change

Verification requirement

Original UTF-8 bytes

Normally changes the signed input

Preserve and verify the original byte sequence

Defined canonical representation

May preserve canonical input

Use the same complete canonicalization profile

Undocumented reserialization

Outcome depends on implementation

Not an interoperable signing contract

Document the algorithm, encoding, canonicalization profile and verification order. Reject ambiguous input and verify the intended envelope before acting on its contents. Do not let an intermediary choose an undocumented reserialization rule and call the resulting signature equivalent.

84. Why can JCS be unsuitable for arbitrary-precision financial numbers?

JCS relies on the specified ECMAScript-compatible number serialization and requires numbers representable as IEEE 754 double precision. An arbitrary-precision decimal value cannot simply be rounded into that model without changing its meaning.

A high-precision amount represented as a JSON number may already lose information when a binary64 consumer parses it. Canonicalizing that rounded value does not restore the original amount. The signature would authenticate the rounded representation, not the intended exact decimal.

For protocols needing exact large integers or decimal precision, define a string representation with an explicit grammar and application semantics, or choose another compatible protocol. Canonicalization and financial equivalence are separate decisions; a fixed decimal spelling also needs a policy for trailing zeros and signs.

85. Does JSON canonicalization normalize Unicode strings?

JCS preserves Unicode string data; it does not silently normalize strings into NFC or another Unicode normalization form. Two visually similar strings can therefore remain distinct and produce different canonical bytes.

For example, a precomposed accented character and a base character followed by a combining mark can render similarly while containing different code points. Treating them as the same account name is an application-level identity policy, not a consequence of parsing JSON.

import json
import unicodedata

left = json.loads('"\u00e9"')
right = json.loads('"e\u0301"')
assert left != right
assert unicodedata.normalize("NFC", left) == unicodedata.normalize("NFC", right)
import json
import unicodedata

left = json.loads('"\u00e9"')
right = json.loads('"e\u0301"')
assert left != right
assert unicodedata.normalize("NFC", left) == unicodedata.normalize("NFC", right)
import json
import unicodedata

left = json.loads('"\u00e9"')
right = json.loads('"e\u0301"')
assert left != right
assert unicodedata.normalize("NFC", left) == unicodedata.normalize("NFC", right)

If normalization is required, define when it occurs and which fields it applies to, preferably before the signed representation is created. Unannounced normalization after signature verification or during lookup can create inconsistent identity and audit behavior. Preserve original text when the product needs faithful display or evidence.

86. How should a service handle lone surrogate escapes?

A JSON text can contain escape sequences that do not represent a valid Unicode scalar value, such as an unpaired surrogate. RFC 8259 identifies interoperability problems for such inputs: libraries can reject them, preserve code units or fail during later encoding.

The fact that one parser accepts an escaped surrogate does not mean the value can safely cross a UTF-8 boundary or be canonicalized. JCS requires invalid Unicode data to cause an error rather than producing a canonical result.

Adopt an explicit interoperable Unicode policy at ingestion and test the parser-to-storage-to-output path. Avoid replacing malformed text silently when identity or signatures depend on exact content. A replacement character changes the data and should not masquerade as successful faithful processing.

87. How should a JSON endpoint handle UTF-8 and byte-order marks?

RFC 8259 requires UTF-8 for JSON exchanged outside a closed ecosystem and says generators must not add a byte-order mark to network-transmitted JSON. Parsers may ignore a BOM for interoperability, so acceptance can differ between components.

Validate the transport decoding and JSON syntax as separate stages. A client that sends UTF-16 bytes to an endpoint expecting UTF-8 has a different problem from a UTF-8 document containing a syntax error.

For a strict public contract, emit UTF-8 without a BOM and document the input policy. Test signed bytes before transformations required by neither the signature protocol nor transport contract. Do not assume a parser’s convenient acceptance of alternative encodings defines the API standard.

88. Where should JSON depth and size limits be enforced?

Enforce limits before and during expensive processing, not only after a complete object tree has been allocated. Bound transport bytes, decompressed size where relevant, nesting depth, member counts and value lengths according to the endpoint’s legitimate workload.

A small compressed request can expand into a much larger JSON body. Likewise, deeply nested arrays may consume parser stack or validation resources even when the total byte count is modest. A single maximum-body-size rule does not cover both cases.

Coordinate proxy, decompressor, parser and validator limits so the narrowest unexpected layer does not produce confusing failures. Return a controlled error and stop consuming work when the contract permits. Test boundary values with small, bounded fixtures rather than stress-testing shared infrastructure.

89. How can numeric literals exhaust resources even when JSON syntax is valid?

An extremely long integer or exponent can create disproportionate work in arbitrary-precision parsing or downstream arithmetic. JSON grammar describes valid syntax; it does not prescribe unlimited numeric precision or computational resources.

A schema maximum may be checked only after the parser has constructed the number. For untrusted requests, a numeric-token length limit or parser-level constraint can therefore be necessary in addition to application range checks.

Define acceptable magnitude, precision and scale for each field. Reject out-of-contract values rather than letting one component round them while another allocates a huge integer. Include exponent forms and underflow or overflow behavior in interoperability tests, not just ordinary decimal values.

90. Does JSON.parse itself cause prototype pollution?

Parsing a property named __proto__ is not the same as changing the prototype of every object. The danger commonly appears when parsed untrusted data is later copied or recursively merged using operations that interpret special property names or inherited properties unsafely.

A generic configuration merge can turn an otherwise ordinary parsed key into a mutation of a target object’s prototype. The relevant boundary is the complete parse-and-use path, not a claim that JSON syntax itself executes code.

Prefer allowlisted configuration fields and data structures appropriate for untrusted keys. Review nested constructor and prototype paths as well as __proto__, and use maintained merge utilities with the required protections. Rejecting one spelling without understanding the merge algorithm is not a complete defense.

91. How can schema reference resolution become an SSRF risk?

A validator that automatically retrieves arbitrary remote $ref targets can make network requests chosen by the schema author. If schemas are untrusted, resolution can expose internal services or create uncontrolled dependency and availability risks.

An application accepting uploaded schemas should not treat every URI as permission to fetch that location. A schema identifier can be a logical identifier mapped to a preloaded resource; it does not require unrestricted network access.

Use a controlled registry of approved resources, pin versions and limit reference depth and total work. Keep validation deterministic when a remote host changes or becomes unavailable. Apply the policy to all supported reference mechanisms rather than protecting only the first document URL.

92. Why can a schema pattern become a denial-of-service issue?

A JSON Schema pattern delegates matching to regular-expression behavior, and some engines can take excessive time on particular patterns and near-matching inputs. A short schema is not necessarily cheap to evaluate.

Nested repetition combined with a long failing suffix is a classic risk pattern. A maxLength limit can reduce exposure, but the limit must be checked early enough and chosen with the engine’s behavior in mind.

Review untrusted or configurable patterns, constrain input sizes and use suitable engine or execution limits. Test bounded representative worst cases without intentionally exhausting a shared process. Keep syntax portability separate from runtime cost: two validators can support similar patterns with different performance characteristics.

93. How should authorization work for JSON Patch paths?

Authorize the actual operation and resolved target, not just whether the patch document matches its schema. A syntactically valid path can still address a field the caller must not change.

For move and copy operations, inspect the source path as well as the destination. Decode JSON Pointer escapes correctly before comparing path segments; raw string-prefix checks can confuse similarly named fields or escaped property names.

Apply field-level rules to the resulting document and relevant intermediate operations according to the API contract. A generic permission to update a profile should not imply permission to change ownership or server-managed audit fields. Validation describes structure; authorization decides who may perform the change.

94. Why can a JSON Patch test fail when host-language equality says two values match?

JSON Patch test uses JSON-type-aware equality, not a language’s loose equality or serialized-text comparison. Numbers compare by numeric value; strings remain strings, array position matters, and object member order does not.

Target and expected value

RFC 6902 test outcome

Reason

1 and 1.0

Equal

Same numeric value

1 and "1"

Unequal

Different JSON types

true and 1

Unequal

Boolean versus number

{"a":1,"b":2} and {"b":2,"a":1}

Equal

Object order is irrelevant

[1,2] and [2,1]

Unequal

Array positions differ

Python’s True == 1 is true, so directly substituting Python equality would accept the wrong boolean-versus-number case. Comparing serialized strings would make the opposite mistake for reordered objects. A patch engine must implement the specified recursive comparison.

Include these cases in engine acceptance tests and constrain numeric precision before comparison. If a parser already rounded distinct large numbers to one value, the test cannot reconstruct the original distinction. These are specification-derived expectations, not results from an executed patch engine.

95. Can an empty JSON Merge Patch change a scalar or array into an object?

Yes. When the patch is an object but the target is not, Merge Patch first treats the target as an empty object. An empty object patch therefore preserves an existing object but replaces a scalar, null or array with an empty object.

Target

Patch

Result

{"a":1}

{}

{"a":1}

7

{}

{}

[1,2]

{}

{}

{"settings":false}

{"settings":{}}

{"settings":{}}

The nested example matters during configuration migrations: an editor that emits an empty settings object can erase a prior boolean representation even though the user supplied no child values. Describing every empty object patch as a no-op is incorrect.

Validate the resulting resource against its allowed shape and enforce whether callers may change a field’s type. If conversion is forbidden, reject the request through the endpoint’s validation policy; do not silently alter the standard merge algorithm while advertising its media type. The table follows RFC 7396 processing rules.

96. How do you evolve a JSON contract with independently deployed producers and consumers?

Plan the compatibility direction explicitly. A new optional field may be safe for a tolerant reader but fail a consumer that rejects unknown properties; changing an enum or numeric representation can break consumers even when the JSON remains valid.

Deploy readers that understand the transition before producers emit the new representation, then migrate stored or queued records and retire legacy support only after observing its disappearance. Include replayed messages and old mobile clients in the timeline.

Use versioned fixtures for producer-consumer combinations and define rollback behavior for data already emitted. A schema version number does not itself implement compatibility. Monitor the actual population of versions rather than assuming a completed server deployment means every consumer has upgraded.

97. How should an audit pipeline distinguish a number’s value from its original spelling?

Parsing commonly preserves a numeric value while discarding its original lexeme. Tokens such as 1, 1.0 and 1e0 can represent the same number, yet differ as evidence of what the producer sent. Decide whether the audit contract needs values, exact token text or the complete original bytes.

const assert = require("node:assert/strict");
const spellings = ["1", "1.0", "1e0"];
const values = spellings.map(text => JSON.parse(text));
assert.deepEqual(values, [1, 1, 1]);
assert.deepEqual(values.map(value => JSON.stringify(value)), ["1", "1", "1"]);
const assert = require("node:assert/strict");
const spellings = ["1", "1.0", "1e0"];
const values = spellings.map(text => JSON.parse(text));
assert.deepEqual(values, [1, 1, 1]);
assert.deepEqual(values.map(value => JSON.stringify(value)), ["1", "1", "1"]);
const assert = require("node:assert/strict");
const spellings = ["1", "1.0", "1e0"];
const values = spellings.map(text => JSON.parse(text));
assert.deepEqual(values, [1, 1, 1]);
assert.deepEqual(values.map(value => JSON.stringify(value)), ["1", "1", "1"]);

This Node example demonstrates that reserialization cannot recover the decimal point or exponent spelling. Multiplying a parsed value or formatting it to two decimal places creates a new representation; it does not establish what was received.

For exact-byte evidence, retain the original payload under bounded access and retention controls and associate it with the interpreted record. Token-aware parsing is another option when only selected numeric lexemes are needed. Do not assume newer parser extensions exist in every deployed runtime, and keep lexical fidelity separate from the numeric range contract.

98. Can a JSON round trip preserve negative zero?

JSON number syntax permits -0, but a language’s parsed representation and serializer can treat its sign differently. JavaScript can represent negative zero, while JSON.stringify serializes that numeric value as 0.

If the sign of zero carries meaning in a numerical application, ordinary JSON numeric round trips may not preserve the required information. Equality checks can also hide the distinction unless the test deliberately examines it.

const assert = require("node:assert/strict");
const value = JSON.parse("-0");
assert.equal(Object.is(value, -0), true);
assert.equal(JSON.stringify(value), "0");
assert.equal(Object.is(JSON.parse(JSON.stringify(value)), -0), false);
const assert = require("node:assert/strict");
const value = JSON.parse("-0");
assert.equal(Object.is(value, -0), true);
assert.equal(JSON.stringify(value), "0");
assert.equal(Object.is(JSON.parse(JSON.stringify(value)), -0), false);
const assert = require("node:assert/strict");
const value = JSON.parse("-0");
assert.equal(Object.is(value, -0), true);
assert.equal(JSON.stringify(value), "0");
assert.equal(Object.is(JSON.parse(JSON.stringify(value)), -0), false);

Define whether negative zero is equivalent to zero in the data contract. If it is meaningful, use an explicit tagged representation rather than relying on incidental serializer behavior. JCS also follows the specified number serialization, so canonicalization is not a way to retain a distinction it intentionally removes.

99. What makes a date-time string an interoperable contract?

JSON has no native date-time type. Define the accepted string format, timezone or offset requirements, precision and interpretation of missing information, and ensure the chosen validator actually enforces the intended format rules.

A timestamp with an offset can identify an instant without preserving the regional timezone rules needed for a future recurring appointment. A local date-time without an offset cannot be converted to an instant unambiguously around some daylight-saving transitions.

Keep instant, local calendar value and named timezone concepts separate. In JSON Schema 2020-12, format is an annotation by default under the format-annotation vocabulary; assertion behavior requires appropriate vocabulary and implementation support. Do not assume the word date-time alone activates every application check.

100. Do contentEncoding and contentMediaType validate embedded binary content?

In JSON Schema 2020-12, content keywords describe content carried in strings; they are not a blanket guarantee that a validator decoded and fully validated that content. Implementations should not automatically decode and validate it by default.

A string annotated as base64 carrying an image may still need explicit decoding limits, media-type verification and application-specific checks. Base64 validity alone does not establish that the bytes form a safe or acceptable image.

If the service needs content validation, make that an explicit bounded processing stage with its own errors and resource limits. Avoid uncontrolled decompression or recursive parsing of embedded formats. Keep structural JSON validation distinct from inspecting the decoded payload.

101. How is a JSON-LD context different from a JSON Schema?

A JSON-LD context maps terms to linked-data identifiers and supplies interpretation rules. A JSON Schema describes structural and value constraints. A document can be valid JSON while needing JSON-LD processing to determine the intended graph meaning.

Changing a context can change the meaning of an unchanged property name. A schema that merely requires that property to contain a string does not establish that the linked-data identifier has the intended meaning.

Pin and govern context dependencies when semantic stability matters, and control remote loading rather than assuming it is harmless metadata. Use the appropriate graph or application validation alongside structural validation. Neither a context nor a schema automatically substitutes for the other.

102. When would you choose CBOR instead of JSON?

CBOR provides a binary representation with features such as byte strings and a richer data model, which can suit constrained transport or typed binary data. JSON offers broad text tooling and human inspectability. Choose from measured message and implementation requirements.

An image encoded in a JSON string needs a representation such as base64, whereas CBOR can carry bytes directly. That potential saving must be weighed against decoder availability, debugging workflow and compatibility with existing clients.

Define the permitted CBOR profile and deterministic-encoding rules if signing is involved. Conversion to JSON can lose distinctions such as non-string map keys or tagged values. Neither format eliminates schema, resource-limit or authorization requirements.

103. Why should JSON5 support stop at an explicit boundary?

JSON5 intentionally accepts human-friendly syntax that strict JSON does not, including comments and trailing commas. It can be appropriate for hand-maintained configuration, but accepting it silently at a JSON API boundary changes the contract.

A configuration loader might parse JSON5 and emit strict JSON for downstream services. It must also address values such as Infinity or NaN that JSON5 can represent but strict JSON cannot carry as numbers.

Document which parser is used at each boundary and reject unsupported values during conversion. A permissive parser in one component can hide invalid output until another component fails. Do not advertise strict JSON conformance solely because a JSON5 parser accepted the text.

104. Why is JSONP not a substitute for a JSON API with CORS?

JSONP returns executable JavaScript, typically invoking a callback, rather than a JSON document. Its script-loading behavior differs fundamentally from fetching JSON under the browser’s cross-origin request controls.

A response wrapped in a callback cannot be treated as inert structured data simply because its argument resembles JSON. Loading it executes code in the page context, and callback handling adds another injection-sensitive boundary.

For modern browser APIs, define an appropriate CORS policy and authentication model and return the documented JSON media type. CORS is not authorization: non-browser clients and allowed browser origins still need correct server-side access checks. Avoid turning sensitive endpoints into executable script responses.

105. How can JSON logging still allow misleading or unsafe log output?

A proper JSON serializer escapes control characters within string values, but later rendering or concatenation can undo that protection. Logging also risks exposing secrets regardless of whether each record is syntactically valid.

If a viewer renders an escaped newline as a new visual record, an attacker-controlled message may appear to create an operator-authored entry. If a service builds log lines by string concatenation, it can produce malformed records before the viewer is involved.

Use structured logging, stable event fields and context-aware display escaping. Redact sensitive fields before they enter durable logs, and test error paths as well as successful requests. Preserve correlation and diagnostic value without recording entire untrusted payloads by default.

106. Why is valid JSON not automatically safe inside an HTML script element?

HTML parsing rules still apply when JSON text is embedded in a page. A string containing a closing script sequence can terminate the element even if the string would be perfectly valid within a standalone JSON document.

The same concern applies to a non-executable script element used to hold application/json data: the HTML parser still recognizes the closing tag. JSON escaping alone is not a complete HTML-context escaping strategy.

Prefer a separate JSON response where practical. If embedding is necessary, use a serializer or framework explicitly designed for that context, commonly escaping the less-than character as a JSON Unicode escape. Test the rendered HTML boundary rather than proving only that JSON.parse accepts the original string.

107. How can a streaming import offer all-or-nothing visibility without buffering the whole JSON file?

Separate bounded parsing from publication. Stream validated records into durable staging under an import identifier, then publish only after the closing document boundary, expected counts and domain checks succeed. Memory can stay bounded while staging storage grows with the import.

Suppose 999 records are valid but the final record is malformed. Directly inserting each record into the live dataset exposes a partial import. With staging, readers continue to see the prior dataset; the failed import is marked for cleanup, and no success marker is issued.

An atomic pointer switch to a completed immutable dataset can provide one publication boundary when the storage system supports it. Independent writes across several stores do not become atomic merely because a completion flag exists: readers must honor the same manifest and consistency model.

Use stable import and record identities for restart, bound disk use and staging lifetime, and distinguish parsed, staged and published counts. A lost response after publication must be reconciled against the committed import identifier before replay. This is an architectural pattern, not a guarantee supplied by JSON or a streaming parser.

108. Why must a JSON text-sequence parser reject an unterminated top-level number?

A complete-looking scalar may be a truncated longer token. RFC 7464 requires whitespace after a top-level number, true, false or null before accepting that sequence element; a record separator alone does not supply that evidence.

Using RS and LF as names for control bytes, RS 123 RS could be the damaged prefix of 1234. The parser must drop the potentially truncated scalar. RS 123 LF RS supplies the required whitespace boundary. Likewise, true without following whitespace could be the prefix of invalid trueish.

Encoders emit LF after each JSON text. Parsers can recover at the next RS and report the dropped record, but recovery does not prove that every intended record survived. Objects, arrays and strings are self-delimiting; treating all values alike misses the scalar-specific truncation rule.

Keep quarantined-record counts and source progress distinct from accepted-record counts. Test raw byte fixtures with the selected sequence implementation; successfully parsing 123 as a standalone JSON text does not test sequence truncation handling.

109. Why should a signed JSON envelope bind its schema and intended use?

A valid signature authenticates the signed representation under its cryptographic protocol; it does not guarantee that every consumer assigns that representation the same business meaning. Bind the intended message type, version, audience and other required context inside the authenticated envelope.

If one service interprets amount as cents and another as whole currency units, the same authenticated numeric value can trigger different actions. An unsigned schema-version header that changes interpretation undermines the meaning the signature was supposed to protect.

Validate the authenticated version against an approved schema and reject unsupported contexts before acting. Use the protocol’s replay protections where required. Keep cryptographic verification, structural validation and authorization as distinct checks whose results are all necessary for acceptance.

110. When do dynamic references matter in composed JSON Schemas?

In Draft 2020-12, $dynamicRef and $dynamicAnchor support reference resolution through dynamic scope, which is useful for extensible recursive schemas. They are not merely alternate spellings for a fixed $ref.

A reusable tree schema can define a recursive node, while a wrapper extends the rule that should also apply to nested nodes. With the appropriate dynamic anchor and reference design, the extended definition can participate during recursive validation rather than affecting only the root.

Use the declared dialect and a validator that supports the vocabulary, and test both root and nested failures. Pin resources in a local registry when reproducibility matters. Resolve identifier and scope behavior deliberately; replacing every $ref with $dynamicRef does not automatically make a schema extensible.

111. Why can stopping after the first successful anyOf branch break unevaluatedProperties?

When evaluation annotations are needed, successful anyOf branches can each contribute evaluated properties. A validator cannot always stop after one passing branch merely because the boolean anyOf result is already known.

from jsonschema import Draft202012Validator

schema = {
    "type": "object",
    "anyOf": [
        {"required": ["a"], "properties": {"a": {"type": "integer"}}},
        {"required": ["b"], "properties": {"b": {"type": "string"}}}
    ],
    "unevaluatedProperties": False
}
Draft202012Validator.check_schema(schema)
validator = Draft202012Validator(schema)
assert validator.is_valid({"a": 1, "b": "ok"})
assert validator.is_valid({"a": 1})
assert not validator.is_valid({"a": 1, "b": 2})
assert not validator.is_valid({"a": 1, "extra": True})
from jsonschema import Draft202012Validator

schema = {
    "type": "object",
    "anyOf": [
        {"required": ["a"], "properties": {"a": {"type": "integer"}}},
        {"required": ["b"], "properties": {"b": {"type": "string"}}}
    ],
    "unevaluatedProperties": False
}
Draft202012Validator.check_schema(schema)
validator = Draft202012Validator(schema)
assert validator.is_valid({"a": 1, "b": "ok"})
assert validator.is_valid({"a": 1})
assert not validator.is_valid({"a": 1, "b": 2})
assert not validator.is_valid({"a": 1, "extra": True})
from jsonschema import Draft202012Validator

schema = {
    "type": "object",
    "anyOf": [
        {"required": ["a"], "properties": {"a": {"type": "integer"}}},
        {"required": ["b"], "properties": {"b": {"type": "string"}}}
    ],
    "unevaluatedProperties": False
}
Draft202012Validator.check_schema(schema)
validator = Draft202012Validator(schema)
assert validator.is_valid({"a": 1, "b": "ok"})
assert validator.is_valid({"a": 1})
assert not validator.is_valid({"a": 1, "b": 2})
assert not validator.is_valid({"a": 1, "extra": True})

Both branches succeed for a=1 and b="ok", so both properties are evaluated. For b=2, the b branch fails and contributes no successful evaluation for that property; the a branch still makes anyOf true, but the outer closure rejects b.

This separates a branch-selection failure from a closure failure and catches a misleading optimization. Test successful combinations and failing alternatives when upgrading validators or reorganizing schemas. Mentioning a property somewhere in a branch is not sufficient to admit it.

112. Should clients depend on the first validation error returned?

Usually they should depend on a documented application error contract rather than a validator’s incidental traversal order. A document can violate several constraints, and implementations or versions may report them in different orders or aggregate them differently.

An invalid field might fail type, required-structure or branch selection checks at different locations. Optimizing evaluation or switching validators can change which message appears first without changing the valid-or-invalid result.

Normalize errors into stable codes and instance locations where clients need automation, while retaining detailed diagnostics internally. Avoid exposing full failing values that may contain secrets. Test the promised error contract, not the exact prose of every third-party validator message.

113. What should a property-based JSON test corpus explore?

Generate values near the boundaries that matter to the contract: nesting, Unicode, numeric magnitude, empty containers, missing fields and alternate valid representations. Pair generated inputs with explicit properties rather than assuming random input automatically provides useful coverage.

For a serializer supporting a constrained data model, one property might be semantic round-trip preservation for every generated value in that model. Invalid cases need a separate generator and a clear expected rejection policy.

Use fixed seeds or saved minimized failures for reproducibility and keep resource bounds small. Include hand-written regression cases for discovered bugs. Passing many generated examples supplies evidence about those tested properties; it is not proof of universal parser correctness or security.

114. Why can a successful serialize-parse round trip hide a bug?

A round trip can preserve the implementation’s own interpretation while losing information that the original protocol needed. It can also compare values using an equality operation that ignores relevant distinctions.

A parser that silently keeps the last duplicate member can serialize its resulting map and parse it again without any mismatch. The test passes even though the original ambiguity has disappeared. Negative zero, numeric lexemes and object order provide other examples depending on the contract.

Equivalence target

May ignore

Must still preserve

Exact bytes

Nothing in the byte sequence

Encoding, whitespace and order

Parsed JSON values under a profile

Permitted lexical differences

All distinctions retained by that profile

Domain meaning

Documented representation alternatives

Business identity, units and required precision

Define the equivalence relation being tested: exact bytes, parsed values, numeric value or domain meaning. Compare against independent fixtures or implementations where appropriate. A metamorphic property is useful only when its assumptions exclude the losses the application considers unacceptable.

115. How would you build a useful differential-parser harness?

Feed the same bounded input bytes to independently configured parsers and compare acceptance and normalized results under an explicit contract. Record parser versions and numeric or duplicate-name policies so a difference can be interpreted rather than merely counted.

Include valid boundary cases and deliberately invalid inputs. A Python parser preserving a large integer while a JavaScript Number-based parser rounds it is an interoperability finding, not automatically evidence that one parser violates JSON syntax.

Classify differences as syntax acceptance, value representation, Unicode handling or resource limits. Preserve the smallest reproducing input and the exact stage that differed. Never use agreement between two permissive parsers as proof that an input conforms to the intended standard.

116. What should be included in a schema-validation cache key?

Cache the compiled schema together with its dialect, resolved resource versions and relevant validator options. Caching only by a mutable schema URL can reuse obsolete rules after a referenced resource changes.

A format-checking option or custom vocabulary can change acceptance even when the top-level schema text is identical. Likewise, a new definition behind an unchanged $ref can alter nested validation without changing the root document.

Use immutable resources or content-addressed bundles and invalidate deliberately. Measure compilation separately from per-instance validation before optimizing. Bound cache size and compilation work when callers can submit many schemas; a cache itself can become an unbounded resource sink.

117. How can contract telemetry remain useful without storing private payloads?

Record the failure category, contract version, producer identity where appropriate and safe structural context, rather than copying entire requests into analytics. The goal is to locate incompatibility while minimizing exposure of field values.

A report that a particular producer version violates the quantity type at a known path can be actionable without retaining a customer address from the same document. Property names can also be sensitive when users control them, so path logging needs a policy.

Track denominators and sampling rules to distinguish a rare edge case from a widespread rollout failure. Limit access and retention for diagnostic samples that are genuinely needed. Redaction should happen before export to logs and telemetry, including validation-error messages generated by libraries.

118. Why does sending the same JSON twice not guarantee an idempotent API call?

JSON describes data, not the server’s effect semantics. Two byte-identical POST bodies can create two resources unless the endpoint defines and enforces an idempotency contract.

A client that times out after sending a payment request may not know whether the first attempt succeeded. Repeating the body with a new request identity can duplicate the business action, even though the JSON is perfectly valid.

Define stable idempotency keys, their scope and lifetime, and behavior when the same key is reused with different content. Persist the key and effect consistently and expose a reconciliation path. If comparing payload hashes, specify whether comparison uses exact bytes or a defined canonical representation.

119. What makes a JSON data migration auditable and reversible?

Preserve the source version and enough original information to explain each transformation, and make the migration resumable with explicit success and failure records. Reversibility depends on the transformation, not merely on retaining a script.

Combining firstName and lastName into one displayName is generally lossy if the original fields are discarded. A reverse script cannot reliably reconstruct where to split every name. Similarly, rounding decimals destroys information that a later parser cannot recover.

Stage and reconcile migrated counts and domain invariants before changing readers. Define rollback for records written after the migration as well as historical records. Retain source data only under the applicable retention policy; auditability does not justify unlimited copies of sensitive content.

120. How would you trace a serialization failure across several services?

Identify the first boundary where bytes or interpretation diverge. Correlate producer serializer version, transport encoding, intermediary transformations, parser options and schema version using a bounded, privacy-aware trace.

If an exact-byte signature fails only after a gateway, compare appropriately protected byte-level evidence around that boundary rather than immediately changing the signing algorithm. If a large identifier changes value, inspect the first Number-based parse or conversion.

Reproduce with a minimal non-sensitive fixture and pin the relevant versions. Separate malformed output, transport corruption, parser-policy differences and schema rejection in the incident timeline. Verify the correction through the whole path, then retain a regression case that exercises the actual failure boundary.

JSON Documentation and Further Reading

These primary specifications and official implementation references cover the format and related contracts. JSON Schema 2020-12 and OpenAPI 3.1.1 are explicit reference versions; library and ECMAScript documentation evolves. RFC 8785 defines the informational JSON Canonicalization Scheme and should not be confused with ordinary key sorting or pretty-printing.

Team Sherlock.sh

Building fraud intelligence for live high-stake video interactions (financial discussions, hiring interviews, board meeting etc).

Catch candidate fraud before it costs you.

Sherlock AI helps you detect AI-assisted, proxy, and deepfake candidates, so every hiring decision is backed by evidence.

Ask AI about Sherlock.sh

Similar Posts