How to check if a string is a valid JSON string?
Validating whether a given string is valid JSON is a common need in many applications—especially when you receive data from untrusted or external sources. The exact approach can vary by language, but the fundamental idea remains the same: try parsing the string, and see if any exceptions or errors occur. Below, we’ll walk through examples in a few popular languages and highlight best practices.
1. General Approach in Most Languages
- Attempt to Parse: Use your language’s built-in (or most commonly used) JSON parser.
- Handle Exceptions: If the parser throws an error, the string isn’t valid JSON.
- Success Case: If no error is thrown, you have valid JSON (assuming the parser is strict).
2. Examples in Different Languages
A. JavaScript
function isValidJSON(str) { try { JSON.parse(str); return true; } catch (e) { return false; } } // Usage console.log(isValidJSON('{"name":"Alice"}')); // true console.log(isValidJSON('{name:"Alice"}')); // false (missing quotes around 'name')
JSON.parse()
: Will throw aSyntaxError
if the string isn’t valid JSON.- Caveat: JavaScript can parse some non-standard JSON (like single quotes or unquoted property names) in certain environments, so be mindful of strictness if you’re dealing with multi-platform requirements.
B. Python
import json def is_valid_json(input_str): try: json.loads(input_str) return True except ValueError: return False # Usage print(is_valid_json('{"name": "Alice"}')) # True print(is_valid_json("{'name': 'Alice'}")) # False, single quotes invalid in strict JSON
json.loads()
: Raises aValueError
if the input is invalid JSON.- Strict Parsing: Python’s built-in
json
module adheres to the official JSON spec.
C. C# (.NET)
Using System.Text.Json
(Recommended in .NET 5+):
using System; using System.Text.Json; public class JSONValidationExample { public static bool IsValidJson(string json) { try { JsonDocument.Parse(json); return true; } catch (JsonException) { return false; } } public static void Main() { Console.WriteLine(IsValidJson("{\"name\":\"Alice\"}")); // True Console.WriteLine(IsValidJson("{name:\"Alice\"}")); // False } }
JsonDocument.Parse(json)
: Throws aJsonException
if invalid.
Using Newtonsoft.Json (Json.NET):
using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; public class JSONValidationNewtonsoft { public static bool IsValidJson(string json) { try { JToken.Parse(json); return true; } catch (JsonReaderException) { return false; } } public static void Main() { Console.WriteLine(IsValidJson("{\"name\":\"Alice\"}")); // True Console.WriteLine(IsValidJson("{name:\"Alice\"}")); // False } }
D. Java with Gson
import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; public class JSONValidation { private static final Gson gson = new Gson(); public static boolean isValidJson(String json) { try { gson.fromJson(json, Object.class); return true; } catch (JsonSyntaxException e) { return false; } } public static void main(String[] args) { System.out.println(isValidJson("{\"name\":\"Alice\"}")); // true System.out.println(isValidJson("{name:\"Alice\"}")); // false } }
fromJson(json, Object.class)
: ThrowsJsonSyntaxException
if invalid.- Other Libraries:
Jackson
orJSON-P
can be similarly used.
3. Edge Cases to Consider
- Empty String: An empty string
""
is invalid JSON. - Whitespace: Some parsers may allow whitespace-only strings, but typically that’s invalid JSON.
null
Input: In many languages,null
is not valid JSON.- Trailing Commas: Most official JSON parsers do not allow trailing commas in objects or arrays.
- Additional Fields: Even if your app expects certain fields, that’s domain validation, not JSON syntax validation. A JSON can be syntactically valid but logically incorrect for your application.
4. Beyond Syntax: Schema Validation
If you need to confirm not only the syntax but also the structure (like required fields, data types, etc.), you can use JSON Schema. This approach allows you to define a schema and check if the JSON conforms to it. Libraries for JSON Schema validation exist for most major languages.
Level Up Your Coding and System Design Skills
Working with JSON effectively is crucial in modern software development. If you’re eager to refine your engineering skill set, consider these courses from DesignGurus.io:
-
Grokking the Coding Interview: Patterns for Coding Questions
- Explore 20+ coding patterns to tackle interview challenges.
-
Grokking the System Design Interview
- Learn how to design and scale distributed systems—an essential skill for building APIs that serve or validate JSON data.
Final Thoughts
Validating JSON comes down to trying to parse the string and catching any parsing errors. This method is reliable and simple. For deeper checks (like ensuring specific fields are present), combine syntax validation with schema checks or other logical verifications. By leveraging these techniques, you can confidently handle user-generated or external JSON data in your applications.