As reported: Amazon SDE 3 DSA round (Nov 2025), first of two questions: validate a JSON string given in prettified form.
Given a string s, return true if it is a valid JSON text and false otherwise. Do not use a JSON library — write the validator.
The input is usually pretty-printed (newlines and indentation), but any amount of whitespace between tokens is allowed.
Example 1
{
"name": "Alice",
"age": 30,
"tags": ["admin", "dev"],
"manager": null
}
Output: true
Example 2
{
"name": "Alice",
"tags": ["admin", "dev"],
}
Output: false trailing comma before }
Example 3
[1, 2, 3]
Output: true the top-level value need not be an object
Rules (standard JSON)
- A value is an object
{ "key": value, … }, an array[value, …], a string, a number,true,falseornull. The whole text is one value, with optional whitespace around it. - Whitespace is only space, tab,
\nand\r. - Object keys are strings. Duplicate keys are allowed.
- Strings use double quotes. Inside a string,
"and\must be escaped, and raw control characters (code below0x20, e.g. a literal tab) are not allowed. Valid escapes:\"\\\/\b\f\n\r\tand\uXXXXwith exactly four hex digits. - Numbers: optional
-, then0or a digit1-9followed by digits (no leading zeros, no+), optionally.with at least one digit, optionallye/E, an optional sign and at least one digit. - Not allowed: trailing commas, comments, single quotes, unquoted keys,
NaN,Infinity.
Constraints: 1 ≤ s.length ≤ 2·10^5; s holds printable ASCII characters plus whitespace and control characters; nesting depth ≤ 500.
Code runner format: one line: s as a JSON-encoded string (so newlines appear as \n). Implement isValidJson(s); the harness prints true or false.