Skip to Content

JSON Formatter

JSON Formatter is an online tool for real-time JSON validation, formatting (prettify), and minification. Features error detection with detailed error messages.

?Enter JSON

📝 Input JSON

Lines: 0Characters: 0Size: 0 bytes

✨ Result

Validate and format JSON (JavaScript Object Notation). Add indentation for readability or remove whitespace to reduce size.

Features

  • Real-time Validation: Automatically validates JSON as you type
  • Format (Prettify): Add indentation for better readability
  • Minify: Remove unnecessary whitespace to reduce size
  • Configurable Indentation: Choose 2 or 4 spaces
  • Error Detection: Displays detailed error messages with line information
  • Statistics: Shows line count, character count, and byte size
  • Sample Data: Load example JSON with one click
  • One-Click Copy: Copy formatted/minified JSON to clipboard

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data interchange format. It's easy for humans to read and write, and easy for machines to parse and generate.

Key Characteristics

  1. Text-based: Human-readable format
  2. Language-independent: Used across all programming languages
  3. Self-describing: Data structure is inherent
  4. Hierarchical: Supports nested structures

Basic Structure

{
"string": "text value",
"number": 123,
"boolean": true,
"null": null,
"array": [1, 2, 3],
"object": {
"nested": "value"
}
}

JSON Data Types

1. String

Text enclosed in double quotes:

{
"name": "John Doe",
"email": "john@example.com",
"address": "123 Main St, City, Country"
}

Rules:

  • Must use double quotes (not single quotes)
  • Escape special characters: \", \\, \n, \t

2. Number

Numeric values (integer or floating-point):

{
"integer": 42,
"float": 3.14159,
"negative": -10,
"exponential": 1.5e+3,
"zero": 0
}

Rules:

  • No quotes around numbers
  • Can be negative
  • Supports exponential notation

3. Boolean

True or false values:

{
"isActive": true,
"isDeleted": false,
"hasPermission": true
}

Rules:

  • Must be lowercase (true or false)
  • No quotes

4. Null

Represents absence of value:

{
"middleName": null,
"profileImage": null
}

5. Array

Ordered list of values:

{
"numbers": [1, 2, 3, 4, 5],
"strings": ["apple", "banana", "cherry"],
"mixed": [1, "two", true, null, {"key": "value"}],
"nested": [[1, 2], [3, 4], [5, 6]]
}

Rules:

  • Enclosed in square brackets []
  • Values separated by commas
  • Can contain any JSON data type

6. Object

Collection of key-value pairs:

{
"user": {
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"roles": ["admin", "user"]
}
}

Rules:

  • Enclosed in curly braces {}
  • Keys must be strings (in double quotes)
  • Key-value pairs separated by commas
  • Colon separates key and value

Common JSON Errors

1. Missing Quotes Around Keys

// ❌ WRONG
{
name: "John"
}

// ✅ CORRECT
{
"name": "John"
}

2. Trailing Commas

// ❌ WRONG
{
"name": "John",
"age": 30, // Trailing comma
}

// ✅ CORRECT
{
"name": "John",
"age": 30
}

3. Single Quotes

// ❌ WRONG
{
'name': 'John'
}

// ✅ CORRECT
{
"name": "John"
}

4. Comments

// ❌ WRONG - JSON doesn't support comments
{
"name": "John", // User's name
"age": 30
}

// ✅ CORRECT
{
"name": "John",
"age": 30
}

5. Undefined Values

// ❌ WRONG
{
"value": undefined
}

// ✅ CORRECT - Use null
{
"value": null
}

Use Cases

1. API Responses

// Fetch API response
const response = await fetch('https://api.example.com/users');
const data = await response.json();

// Format for logging
console.log(JSON.stringify(data, null, 2));

2. Configuration Files

// package.json
{
"name": "my-project",
"version": "1.0.0",
"scripts": {
"start": "node index.js",
"test": "jest"
},
"dependencies": {
"express": "^4.18.0"
}
}

3. Data Storage

// LocalStorage
const user = {
id: 1,
name: "John Doe",
preferences: {
theme: "dark",
notifications: true
}
};

// Store
localStorage.setItem('user', JSON.stringify(user));

// Retrieve
const storedUser = JSON.parse(localStorage.getItem('user'));

4. Data Exchange

// Client sends JSON
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'John Doe',
email: 'john@example.com'
})
});

// Server responds with JSON
app.post('/users', (req, res) => {
const user = req.body;
// Process user...
res.json({
success: true,
data: user
});
});

Programming Examples

JavaScript

// Parse JSON string
const jsonString = '{"name":"John","age":30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "John"

// Convert to JSON string
const user = {
name: "John Doe",
age: 30,
email: "john@example.com"
};

// Compact format
const compact = JSON.stringify(user);
console.log(compact);
// {"name":"John Doe","age":30,"email":"john@example.com"}

// Formatted (prettified)
const formatted = JSON.stringify(user, null, 2);
console.log(formatted);
/*
{
"name": "John Doe",
"age": 30,
"email": "john@example.com"
}
*/

// Custom replacer function
const filtered = JSON.stringify(user, ['name', 'age'], 2);
// Only includes specified keys

Python

import json

# Parse JSON string
json_string = '{"name":"John","age":30}'
data = json.loads(json_string)
print(data['name']) # "John"

# Convert to JSON string
user = {
'name': 'John Doe',
'age': 30,
'email': 'john@example.com'
}

# Compact format
compact = json.dumps(user)
print(compact)

# Formatted (prettified)
formatted = json.dumps(user, indent=2)
print(formatted)

# Write to file
with open('user.json', 'w') as f:
json.dump(user, f, indent=2)

# Read from file
with open('user.json', 'r') as f:
loaded_user = json.load(f)

PHP

<?php
// Parse JSON string
$jsonString = '{"name":"John","age":30}';
$data = json_decode($jsonString);
echo $data->name; // "John"

// Associative array
$dataArray = json_decode($jsonString, true);
echo $dataArray['name']; // "John"

// Convert to JSON string
$user = array(
'name' => 'John Doe',
'age' => 30,
'email' => 'john@example.com'
);

// Compact format
$compact = json_encode($user);
echo $compact;

// Formatted (prettified)
$formatted = json_encode($user, JSON_PRETTY_PRINT);
echo $formatted;

// Options
$json = json_encode($user, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
?>

Java

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonExample {
public static void main(String[] args) {
// Create Gson instance
Gson gson = new Gson();

// Parse JSON string
String jsonString = "{\"name\":\"John\",\"age\":30}";
User user = gson.fromJson(jsonString, User.class);
System.out.println(user.getName()); // "John"

// Convert to JSON string
User newUser = new User("John Doe", 30, "john@example.com");

// Compact format
String compact = gson.toJson(newUser);
System.out.println(compact);

// Formatted (prettified)
Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
String formatted = prettyGson.toJson(newUser);
System.out.println(formatted);
}
}

class User {
private String name;
private int age;
private String email;

// Constructor, getters, setters...
}

C#

using System;
using Newtonsoft.Json;

public class JsonExample
{
public static void Main()
{
// Parse JSON string
string jsonString = "{\"name\":\"John\",\"age\":30}";
var user = JsonConvert.DeserializeObject<User>(jsonString);
Console.WriteLine(user.Name); // "John"

// Convert to JSON string
var newUser = new User
{
Name = "John Doe",
Age = 30,
Email = "john@example.com"
};

// Compact format
string compact = JsonConvert.SerializeObject(newUser);
Console.WriteLine(compact);

// Formatted (prettified)
string formatted = JsonConvert.SerializeObject(newUser, Formatting.Indented);
Console.WriteLine(formatted);
}
}

public class User
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}

Format vs Minify

Formatted (Prettified)

Purpose: Improve readability for humans

{
"users": [
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
},
{
"id": 2,
"name": "Jane Smith",
"email": "jane@example.com"
}
]
}

Benefits:

  • Easy to read and debug
  • Clear structure
  • Better for development and documentation

Drawbacks:

  • Larger file size
  • More bandwidth usage

Minified (Compact)

Purpose: Reduce file size for transmission

{"users":[{"id":1,"name":"John Doe","email":"john@example.com"},{"id":2,"name":"Jane Smith","email":"jane@example.com"}]}

Benefits:

  • Smaller file size
  • Faster network transmission
  • Better for production APIs

Drawbacks:

  • Hard to read
  • Difficult to debug

When to Use Each

Use Formatted:

  • Development and debugging
  • Configuration files
  • Documentation
  • Git repositories

Use Minified:

  • Production API responses
  • Browser transmission
  • Large data transfers
  • Performance-critical applications

JSON vs Other Formats

JSON vs XML

FeatureJSONXML
ReadabilityMore conciseMore verbose
Data TypesNative supportStrings only
ArraysNative []Requires structure
Parsing SpeedFasterSlower
File SizeSmallerLarger
AttributesNoYes
CommentsNoYes
// JSON
{
"user": {
"name": "John",
"age": 30
}
}
<!-- XML -->
<user>
<name>John</name>
<age>30</age>
</user>

JSON vs YAML

FeatureJSONYAML
ReadabilityGoodExcellent
Strict SyntaxYesMore flexible
CommentsNoYes
ReferencesNoYes
Multiline StringsEscapedNative
// JSON
{
"database": {
"host": "localhost",
"port": 5432
}
}
# YAML
database:
host: localhost
port: 5432

Best Practices

Do's

  1. Use double quotes: Always use double quotes for strings
  2. Validate before sending: Always validate JSON before transmission
  3. Use meaningful keys: Choose descriptive key names
  4. Keep it simple: Avoid overly nested structures
  5. Use consistent formatting: Maintain consistent indentation

Don'ts

  1. No trailing commas: Remove trailing commas
  2. No comments: JSON doesn't support comments
  3. No single quotes: Use double quotes only
  4. No undefined: Use null instead
  5. No circular references: Avoid circular object references

Security Considerations

JSON Injection

// VULNERABLE: User input directly in JSON
const userInput = '"; alert("XSS"); "';
const json = `{"name": "${userInput}"}`;
// Potential XSS attack

// SECURE: Properly sanitize and validate
const safeJson = JSON.stringify({ name: userInput });
// Automatically escapes special characters

Large JSON Payloads

// Set size limits
app.use(express.json({ limit: '1mb' }));

// Validate before parsing
if (request.headers['content-length'] > 1000000) {
return response.status(413).send('Payload too large');
}

FAQ

Q1. Why won't my JSON parse?

A: Common reasons:

  1. Missing quotes around keys
  2. Trailing commas
  3. Single quotes instead of double quotes
  4. Comments in JSON
  5. Undefined values

Use our tool's error detection to find the exact issue!

Q2. What's the maximum JSON size?

A: No strict limit, but practical limits:

  • Browsers: Usually 5-10 MB for localStorage
  • Node.js: Default 100 KB (configurable)
  • APIs: Often limited to 1-10 MB

Q3. Can JSON contain functions?

A: No. JSON is a data format only. It can't contain functions, dates (as Date objects), or undefined values.

// Will lose function and date objects
const obj = {
name: "John",
greet: function() { console.log("Hello"); }, // Lost
birthdate: new Date() // Converted to string
};

JSON.stringify(obj);
// {"name":"John","birthdate":"2024-01-01T00:00:00.000Z"}

Q4. How do I handle dates in JSON?

A: Convert dates to ISO 8601 strings:

// Sending
const data = {
created: new Date().toISOString()
};
JSON.stringify(data);
// {"created":"2024-01-01T00:00:00.000Z"}

// Receiving
const parsed = JSON.parse(jsonString);
const date = new Date(parsed.created);

Q5. What's the difference between JSON.parse() and eval()?

A: Never use eval() for JSON:

// ❌ DANGEROUS - Security risk
const obj = eval('(' + jsonString + ')');

// ✅ SAFE - Use JSON.parse()
const obj = JSON.parse(jsonString);

eval() executes arbitrary code, making it a security vulnerability. Always use JSON.parse().

Q6. Can I add comments to JSON?

A: No, JSON doesn't support comments. Alternatives:

  1. Use a _comment key (not recommended)
  2. Use JSONC (JSON with Comments) for config files
  3. Document externally