Microsoft
Anonymous User
621
Jan 01, 2026
Jan 01, 2026
Problem Statement
Write a Java function that determines whether a given string is a valid JSON string.
The string may contain arbitrary whitespace (leading, trailing, or internal) and any valid JSON structures, including objects, arrays, strings, numbers, booleans, and null. The function must correctly identify invalid cases such as unquoted keys, trailing commas, malformed numbers, illegal characters, etc.
Input
- A string
srepresenting the potential JSON text.
Output
- Return
trueifsis valid JSON,falseotherwise.
Examples
isValidJson(" { \"name\": \"John\", \"age\": 30, \"car\": null } "); // → true
isValidJson(" { name: \"John\" } "); // → false (unquoted key)
isValidJson("[1, 2, 3]"); // → true
isValidJson("{\"key\": \"value\",}"); // → false (trailing comma)
isValidJson("true"); // → true
isValidJson("null"); // → true
isValidJson(""); // → false
isValidJson("not json"); // → falseConstraints
1 ≤ s.length ≤ 10^6- The function should be efficient enough to handle strings up to 1 million characters.
- No
libraryimport
Requirements
- Provide a clear, reusable static method.
Comments (0)

