JSON for Developers: Syntax, Validation, and Common Mistakes
· 12 min read
Table of Contents
- What is JSON and Why It Matters
- JSON Syntax Rules
- Understanding JSON Data Types
- Common Mistakes and How to Avoid Them
- Validating JSON: Tools and Techniques
- Parsing and Serialization Best Practices
- Security Considerations
- Performance Optimization
- Essential JSON Tools for Developers
- JSON Alternatives and When to Use Them
- Frequently Asked Questions
- Related Articles
What is JSON and Why It Matters
JSON (JavaScript Object Notation) has become the de facto standard for data interchange on the web. Despite its name suggesting a JavaScript connection, JSON is completely language-independent and supported by virtually every modern programming language.
Originally specified by Douglas Crockford in the early 2000s, JSON emerged as a lightweight alternative to XML. Its simplicity and human readability made it the perfect format for APIs, configuration files, and data storage.
Today, JSON powers everything from REST APIs and NoSQL databases to configuration files and data pipelines. Understanding JSON thoroughly isn't just helpful—it's essential for modern software development.
Quick tip: JSON is not a programming language or a database format. It's purely a data serialization format—a way to represent structured data as text.
JSON Syntax Rules
JSON's syntax is deceptively simple, but its strictness catches many developers off guard. Unlike JavaScript objects, JSON has zero tolerance for syntax variations.
Here's a valid JSON example that demonstrates the core structure:
{
"name": "RunDev",
"version": 2,
"features": ["formatter", "validator", "converter"],
"config": {
"theme": "dark",
"autoSave": true
},
"deprecated": null
}
The Non-Negotiable Rules
Every JSON document must follow these strict rules:
- Keys must be double-quoted strings —
"name"is valid, butnameor'name'will cause parsing errors - Strings must use double quotes —
"hello"works,'hello'doesn't - No trailing commas —
[1, 2, 3]is correct,[1, 2, 3,]will fail - No comments allowed — neither
// commentnor/* comment */are valid - Use null, not undefined — JavaScript's
undefineddoesn't exist in JSON - Numbers follow specific formatting — no leading zeros (
10not010), no hex notation, noInfinityorNaN
Why So Strict?
JSON's strictness is intentional. By eliminating ambiguity, JSON ensures that any valid JSON document can be parsed identically across all platforms and languages. This predictability is what makes JSON reliable for data exchange.
The lack of comments is often criticized, but it forces developers to make their data self-documenting through clear key names and structure. For configuration files where comments are needed, consider JSONC (JSON with Comments) or JSON5.
Pro tip: Use our JSON Formatter to automatically fix common syntax errors and ensure your JSON is valid before deployment.
Understanding JSON Data Types
JSON supports exactly six data types. This limited set keeps the format simple while covering most data representation needs.
| Type | Example | Notes |
|---|---|---|
| String | "hello world" |
Must be double-quoted. Supports escape sequences: \n, \t, \u0041, \", \\ |
| Number | 42, 3.14, -1, 1e10 |
No distinction between integer and float. No hex, octal, or special values like Infinity |
| Boolean | true, false |
Lowercase only. "true" is a string, not a boolean |
| Null | null |
Lowercase only. Represents intentional absence of value |
| Array | [1, "two", true] |
Ordered list. Can contain mixed types (though homogeneous arrays are clearer) |
| Object | {"key": "value"} |
Unordered key-value pairs. Keys must be strings and should be unique |
Strings and Escape Sequences
JSON strings support several escape sequences for special characters:
\"— double quote\\— backslash\/— forward slash (optional, but valid)\b— backspace\f— form feed\n— newline\r— carriage return\t— tab\uXXXX— Unicode character (e.g.,\u0041for "A")
Multiline strings must use escape sequences—literal line breaks are not allowed:
{
"correct": "Line 1\nLine 2\nLine 3",
"incorrect": "Line 1
Line 2
Line 3"
}
Numbers: What's Allowed and What's Not
JSON numbers are more restrictive than most programming languages:
- Valid:
42,-17,3.14159,-0.5,1.23e10,1.23e-10 - Invalid:
.5(must be0.5),010(octal notation),0xFF(hex),Infinity,NaN
The JSON specification doesn't define precision limits, but most implementations use IEEE 754 double-precision floating-point, which means integers are safe up to 2^53 - 1 (9,007,199,254,740,991).
Pro tip: For large integers beyond JavaScript's safe integer range, consider storing them as strings to prevent precision loss during parsing.
Objects and Key Uniqueness
While the JSON specification states that object keys should be unique, it doesn't mandate how parsers should handle duplicates. Different implementations behave differently:
- JavaScript's
JSON.parse()keeps the last occurrence - Some validators reject duplicate keys entirely
- Others keep the first occurrence
Best practice: Always ensure your keys are unique to avoid unpredictable behavior across different parsers.
Common Mistakes and How to Avoid Them
Even experienced developers make JSON syntax errors. Here are the most frequent mistakes and their fixes:
| Mistake | Wrong | Correct |
|---|---|---|
| Single quotes | {'name': 'test'} |
{"name": "test"} |
| Trailing comma | {"a": 1, "b": 2,} |
{"a": 1, "b": 2} |
| Unquoted keys | {name: "test"} |
{"name": "test"} |
| Comments | {"a": 1 // comment} |
Remove comments or use JSONC |
| Undefined value | {"a": undefined} |
{"a": null} |
| Leading zeros | {"port": 080} |
{"port": 80} |
| Literal newlines | "line1 |
"line1\nline2" |
| Function values | {"fn": function(){}} |
Not supported—use strings or restructure |
The JavaScript Object Trap
The biggest source of JSON errors is treating it like JavaScript object literal syntax. They look similar but have critical differences:
// Valid JavaScript object
const jsObj = {
name: 'test', // unquoted key, single quotes
age: 30,
active: true,
getData: function() { return this.name; }, // functions allowed
// comment allowed
};
// Valid JSON (as a string)
const jsonStr = `{
"name": "test",
"age": 30,
"active": true
}`;
Remember: JSON is a data format, not code. It can't contain functions, comments, or executable logic.
Character Encoding Issues
JSON must be encoded in UTF-8, UTF-16, or UTF-32. UTF-8 is the most common and recommended encoding. Watch out for:
- BOM (Byte Order Mark) at the start of files—some parsers reject it
- Invalid UTF-8 sequences that can cause parsing failures
- Control characters (U+0000 through U+001F) that must be escaped
Quick tip: Paste your JSON into our JSON Validator to instantly identify syntax errors, encoding issues, and structural problems.
Validating JSON: Tools and Techniques
Validation is crucial for catching errors before they cause runtime failures. Here's how to validate JSON across different environments.
Command Line Validation
Quick validation using built-in tools:
# Python (built-in, available everywhere)
python3 -m json.tool data.json
# Pretty-print and validate
python3 -m json.tool data.json output.json
# jq (powerful JSON processor)
jq . data.json
# jq with error details
jq . data.json || echo "Invalid JSON"
# Node.js one-liner
node -e "console.log(JSON.parse(require('fs').readFileSync('data.json')))"
# Using jsonlint (install via npm)
jsonlint data.json
Programmatic Validation
Validate JSON in your application code:
// JavaScript/Node.js
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
console.error('JSON Error:', e.message);
return false;
}
}
# Python
import json
def is_valid_json(json_str):
try:
json.loads(json_str)
return True
except json.JSONDecodeError as e:
print(f'JSON Error: {e}')
return False
// Go
import "encoding/json"
func isValidJSON(data []byte) bool {
var js json.RawMessage
return json.Unmarshal(data, &js) == nil
}
Schema Validation
Syntax validation only checks if JSON is well-formed. Schema validation ensures the data structure and types match your requirements.
JSON Schema is the standard for defining JSON structure:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
},
"email": {
"type": "string",
"format": "email"
}
},
"required": ["name", "email"]
}
Popular schema validation libraries:
- JavaScript: Ajv (fastest), joi, yup
- Python: jsonschema, pydantic
- Go: gojsonschema, jsonschema
- Java: everit-org/json-schema, networknt/json-schema-validator
Pro tip: Use our JSON Schema Validator to test your schemas against sample data before implementing them in code.
Online Validation Tools
For quick checks during development:
- RunDev JSON Validator — instant validation with detailed error messages
- RunDev JSON Formatter — validate and beautify in one step
- JSONLint — classic online validator
- JSON Schema Validator — test schemas interactively
Parsing and Serialization Best Practices
Parsing converts JSON text into native data structures. Serialization does the reverse. Both operations have performance and security implications.
Safe Parsing Practices
Always wrap JSON parsing in error handling:
// JavaScript - Basic parsing
try {
const data = JSON.parse(jsonString);
// Use data
} catch (error) {
console.error('Failed to parse JSON:', error.message);
// Handle error appropriately
}
// JavaScript - With reviver function
const data = JSON.parse(jsonString, (key, value) => {
// Transform dates from strings
if (key.endsWith('Date') && typeof value === 'string') {
return new Date(value);
}
return value;
});
Serialization Best Practices
Control how objects are converted to JSON:
// JavaScript - Basic serialization
const json = JSON.stringify(data);
// Pretty-print with indentation
const json = JSON.stringify(data, null, 2);
// Custom serialization with replacer
const json = JSON.stringify(data, (key, value) => {
// Remove sensitive fields
if (key === 'password' || key === 'apiKey') {
return undefined;
}
// Convert BigInt to string
if (typeof value === 'bigint') {
return value.toString();
}
return value;
}, 2);
Handling Special Cases
Some JavaScript values don't serialize cleanly:
undefined— omitted from objects, becomesnullin arraysNaNandInfinity— becomenullDateobjects — serialized as ISO 8601 stringsRegExpandFunction— become{}- Circular references — throw errors
const obj = {
a: undefined, // omitted
b: NaN, // becomes null
c: Infinity, // becomes null
d: new Date(), // becomes "2026-03-31T12:00:00.000Z"
e: /regex/, // becomes {}
f: () => {} // becomes undefined (omitted)
};
console.log(JSON.stringify(obj));
// {"b":null,"c":null,"d":"2026-03-31T12:00:00.000Z","e":{}}
Pro tip: Implement custom toJSON() methods on your classes to control serialization behavior and ensure consistent JSON output.
Security Considerations
JSON parsing and handling can introduce security vulnerabilities if not done carefully.
Prototype Pollution
Malicious JSON can pollute JavaScript's prototype chain:
// Dangerous - don't do this
const malicious = '{"__proto__": {"isAdmin": true}}';
const obj = JSON.parse(malicious);
// Now ALL objects have isAdmin: true
Protection strategies:
- Use
Object.create(null)for parsed objects - Validate against a schema before using data
- Never use
eval()orFunction()to parse JSON - Sanitize keys before using them to access object properties
Denial of Service (DoS)
Large or deeply nested JSON can exhaust memory or CPU:
- Set maximum payload size limits
- Limit nesting depth (most parsers default to 512 levels)
- Use streaming parsers for large files
- Implement timeouts for parsing operations
Injection Attacks
When embedding JSON in HTML or SQL:
// Dangerous - XSS vulnerability
const html = `<script>var data = ${JSON.stringify(userData)}</script>`;
// Safe - escape properly
const html = `<script>var data = ${JSON.stringify(userData)
.replace(/</g, '\\u003c')
.replace(/>/g, '\\u003e')}</script>`;
Sensitive Data Exposure
Prevent accidental leakage of sensitive information:
- Use replacer functions to exclude sensitive fields
- Implement proper access controls before serialization
- Never log full JSON payloads containing credentials
- Use separate DTOs (Data Transfer Objects) for API responses
Quick tip: Always validate and sanitize JSON from untrusted sources. Use our JSON Validator to check structure before processing user-submitted data.
Performance Optimization
JSON operations can become bottlenecks in high-performance applications. Here's how to optimize them.
Parsing Performance
Strategies