How to Validate JSON: A Complete Guide for Developers
Invalid JSON is one of the most common causes of API failures and config errors. Here's how to catch problems before they cause outages.
๐ ๏ธ Validate Your JSON Instantly
Paste your JSON and get real-time validation with pinpointed error messages โ completely free.
Open JSON Validator โWhat Does "Valid JSON" Actually Mean?
JSON (JavaScript Object Notation) follows a strict syntax defined by RFC 8259. Unlike JavaScript objects, JSON has no room for flexibility โ a single misplaced comma or unquoted key will make the entire document invalid.
Valid JSON must follow these rules:
- Data is organized in key-value pairs within curly braces
{}for objects - Ordered lists use square brackets
[]for arrays - Keys must be double-quoted strings โ single quotes are not allowed
- Values can be strings, numbers, booleans (
true/false),null, objects, or arrays - No trailing commas after the last element
- No comments (unlike JavaScript)
- Strings must use double quotes, not single quotes
The 7 Most Common JSON Validation Errors
1. Trailing Commas
This is the #1 mistake developers make. JavaScript allows trailing commas, but JSON does not:
// โ Invalid โ trailing comma after "admin"
{
"name": "Alice",
"role": "admin",
}
// โ
Valid
{
"name": "Alice",
"role": "admin"
}
2. Single Quotes Instead of Double Quotes
Python developers frequently hit this when converting dictionaries to JSON:
// โ Invalid
{'name': 'Alice'}
// โ
Valid
{"name": "Alice"}
3. Unquoted Keys
JavaScript object literals allow unquoted keys, but JSON requires them:
// โ Invalid
{name: "Alice"}
// โ
Valid
{"name": "Alice"}
4. Comments in JSON
There are no comments in JSON. Period. If you see // or /* */ in a JSON file, it's technically invalid (though some parsers like JSON5 allow them):
// โ Invalid
{
// user's name
"name": "Alice"
}
// โ
Valid โ use a descriptive key instead
{
"userName": "Alice"
}
5. Missing or Extra Brackets
Deeply nested JSON makes it easy to lose track of opening and closing brackets:
// โ Invalid โ missing closing bracket
{
"users": [
{"name": "Alice"},
{"name": "Bob"}
// โ
Valid
{
"users": [
{"name": "Alice"},
{"name": "Bob"}
]
}
6. Using undefined or NaN
These are JavaScript values that have no equivalent in JSON:
// โ Invalid
{"value": undefined, "count": NaN}
// โ
Valid
{"value": null, "count": 0}
7. Improper String Escaping
Strings containing special characters need proper escaping:
// โ Invalid โ unescaped newline and quote
{"message": "Hello "world"
next line"}
// โ
Valid
{"message": "Hello \"world\"\nnext line"}
How to Validate JSON in Different Languages
JavaScript / Node.js
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
console.error('Invalid JSON:', e.message);
return false;
}
}
// Usage
isValidJSON('{"name": "Alice"}'); // true
isValidJSON("{'name': 'Alice'}"); // false
Python
import json
def is_valid_json(text):
try:
json.loads(text)
return True
except json.JSONDecodeError as e:
print(f"Invalid JSON at line {e.lineno}, col {e.colno}: {e.msg}")
return False
# Usage
is_valid_json('{"name": "Alice"}') # True
is_valid_json("{'name': 'Alice'}") # False
Command Line (jq)
# Validate a JSON file
jq empty myfile.json
# Validate a string
echo '{"name": "Alice"}' | jq empty
# If invalid, jq will print the error and exit with code 1
Go
package main
import (
"encoding/json"
"fmt"
)
func isValidJSON(s string) bool {
var js json.RawMessage
return json.Unmarshal([]byte(s), &js) == nil
}
func main() {
fmt.Println(isValidJSON(`{"name": "Alice"}`)) // true
}
Validation vs. Schema Validation
There's an important distinction between syntax validation and schema validation:
- Syntax validation checks if the JSON is well-formed โ proper brackets, quotes, and data types. This is what
JSON.parse()does. - Schema validation checks if the JSON matches a specific structure โ required fields, value types, string patterns, etc. This requires tools like JSON Schema.
For example, this JSON is syntactically valid but might fail schema validation if "email" is a required field:
// Syntactically valid, but missing required "email"
{
"name": "Alice",
"age": 30
}
For most debugging scenarios, syntax validation is what you need first. Schema validation comes into play when you're building APIs and want to enforce specific data contracts.
Online JSON Validation: The Fastest Approach
When you're debugging a quick API response or config file, the fastest approach is an online validator. No setup, no dependencies โ just paste and check.
Our JSON Formatter & Validator provides:
- Real-time validation โ errors appear as you type
- Pinpointed errors โ see exactly which line and character caused the issue
- Auto-formatting โ once validated, pretty-print with one click
- Privacy โ everything runs in your browser, no data sent to any server
Best Practices for Avoiding JSON Errors
- Never hand-write JSON โ use your language's built-in serializer (
JSON.stringify(),json.dumps(), etc.) - Use a linter in your editor โ VS Code, Try Neon Postgres, and others flag JSON errors in real-time
- Validate before deploying โ add JSON validation to your CI/CD pipeline
- Use JSON Schema for APIs โ enforce structure beyond just syntax
- Test with edge cases โ empty objects, deeply nested data, Unicode characters, large numbers
๐ Format & Validate JSON Online
Found a JSON error? Paste it into our formatter for instant validation, error pinpointing, and pretty-printing.
Open JSON Formatter โRecommended Tools & Resources
Level up your workflow with these developer tools:
Try DigitalOcean → Try Neon Postgres → Clean Code by Robert C. Martin →Dev Tools Digest
Get weekly developer tools, tips, and tutorials. Join our developer newsletter.
Frequently Asked Questions
Can JSON have comments?
No. Standard JSON (RFC 8259) does not support comments. If you need comments in config files, consider JSON5 or JSONC formats, which some tools support.
Why does my JSON work in JavaScript but fail in a validator?
JavaScript object literals are more permissive than JSON โ they allow unquoted keys, trailing commas, single quotes, and comments. JSON is a stricter subset.
How do I validate a large JSON file?
For files under 10MB, an online validator works fine. For larger files, use command-line tools like jq empty largefile.json or python -m json.tool largefile.json.
What's the difference between JSON.parse() and a JSON validator?
JSON.parse() validates syntax and returns a JavaScript object. A dedicated validator may also check schema compliance, format the output, and provide detailed error messages with line numbers.
Related reading: JSON Formatter Online Free ยท How to Fix JSON Errors
Frequently Asked Questions
How do I check if JSON is valid?
Paste your JSON into a validator like devtoolkit.cloud/tools/json-formatter. Programmatically: try JSON.parse(str) in JavaScript or json.loads(str) in Python and catch exceptions. Valid JSON requires double quotes, no trailing commas.
What are the most common JSON errors?
The top JSON errors: trailing commas after the last item, single quotes instead of double quotes, unquoted keys, missing commas between items, and comments (JSON doesn't support comments).
Can JSON have comments?
No. Standard JSON (RFC 8259) does not support comments. Use JSONC (JSON with Comments) or JSON5 if you need comments. Alternatively, add a '_comment' key as a workaround for configuration files.