Microsoft
Anonymous User
563

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 s representing the potential JSON text.

Output

  • Return true if s is valid JSON, false otherwise.

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");                                             // → false

Constraints

  • 1 ≤ s.length ≤ 10^6
  • The function should be efficient enough to handle strings up to 1 million characters.
  • No library import

Requirements

  • Provide a clear, reusable static method.
Comments (0)