JSON for Developers: Syntax, Validation, and Common Mistakes

· 12 min read

Table of Contents

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:

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:

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:

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:

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
line2"
"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:

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:

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:

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:

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:

Denial of Service (DoS)

Large or deeply nested JSON can exhaust memory or CPU:

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:

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