JSON Encoder Encoders
Input
Output
Settings
Developer Guide
JavaScript
// Parse JSON string
const jsonString = '{"name":"John","age":30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // John
// Stringify object to JSON
const data = { name: "John", age: 30, city: "New York" };
const json = JSON.stringify(data, null, 2); // Pretty print
console.log(json);
// Custom replacer function
const filtered = JSON.stringify(data, ['name', 'age']); // Only include specific keys
// Handle errors
try {
const parsed = JSON.parse(jsonString);
} catch (e) {
console.error('Invalid JSON:', e.message);
}
Python
import json
# Parse JSON string
json_string = '{"name":"John","age":30}'
data = json.loads(json_string)
print(data['name']) # John
# Convert to JSON
obj = {"name": "John", "age": 30, "city": "New York"}
json_str = json.dumps(obj, indent=2) # Pretty print
print(json_str)
# Sort keys
json_sorted = json.dumps(obj, sort_keys=True)
# Custom encoder for datetime
import datetime
def json_encoder(obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
raise TypeError(f"Object of type {type(obj)} is not JSON serializable")
json.dumps({"time": datetime.datetime.now()}, default=json_encoder)
PHP
// Parse JSON string
$jsonString = '{"name":"John","age":30}';
$data = json_decode($jsonString);
echo $data->name; // John
// As associative array
$array = json_decode($jsonString, true);
echo $array['name']; // John
// Encode to JSON
$obj = array("name" => "John", "age" => 30, "city" => "New York");
$json = json_encode($obj, JSON_PRETTY_PRINT); // Pretty print
echo $json;
// Handle errors
$result = json_decode($jsonString);
if (json_last_error() !== JSON_ERROR_NONE) {
echo 'JSON Error: ' . json_last_error_msg();
}
// Options
$escaped = json_encode($obj, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
JSON Reference
Data Types
- String: "Hello World"
- Number: 42, 3.14
- Boolean: true, false
- Null: null
- Object: {"key": "value"}
- Array: [1, 2, 3]
Escape Sequences
| \" | Double quote |
| \\ | Backslash |
| \n | Newline |
| \r | Carriage return |
| \t | Tab |
| \b | Backspace |
| \f | Form feed |
| \uXXXX | Unicode |
Best Practices
- Always validate JSON before parsing
- Use pretty print for debugging
- Handle parsing errors gracefully
- Consider using JSON Schema for validation
- Be aware of data type conversions
- Use appropriate encoding options
What is JSON?
JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format that's easy for humans to read and write, and easy for machines to parse and generate. Despite its name suggesting a connection to JavaScript, JSON is language-independent and is supported by most modern programming languages.
How Does JSON Work?
JSON represents structured data using a syntax that's a subset of JavaScript object literal notation. It supports six data types: strings, numbers, booleans, null, objects (collections of key-value pairs), and arrays (ordered lists of values). JSON's simplicity and universality have made it the de facto standard for data exchange in web applications, APIs, and configuration files.
Data Exchange
Universal format for API communication and data transfer between systems.
Validation
Ensure JSON syntax is correct and data structures are properly formatted.
Formatting
Pretty print JSON with proper indentation for better readability.
Minification
Compress JSON by removing unnecessary whitespace for efficient transmission.
Common Use Cases for JSON
- REST APIs: Standard format for sending and receiving data in web services.
- Configuration Files: Store application settings in a human-readable format.
- Data Storage: NoSQL databases like MongoDB use JSON-like documents.
- AJAX Requests: Exchange data between web browsers and servers.
- Mobile Apps: Communicate between mobile applications and backend services.
- Microservices: Inter-service communication in distributed systems.
- Data Export/Import: Transfer data between different systems and applications.
JSON Examples
Basic JSON Object:
{
"name": "John Doe",
"age": 30,
"email": "[email protected]",
"active": true
}
Nested JSON with Arrays:
{
"users": [
{
"id": 1,
"name": "Alice",
"roles": ["admin", "user"]
},
{
"id": 2,
"name": "Bob",
"roles": ["user"]
}
],
"total": 2
}
JSON Schema Example:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "number", "minimum": 0 }
},
"required": ["name"]
}
Frequently Asked Questions
What's the difference between JSON and JavaScript objects?
JSON is a text format with stricter syntax rules: property names must be in double quotes, no comments allowed, and limited data types. JavaScript objects are more flexible, supporting functions, comments, and unquoted property names.
How do I validate JSON?
Use our validator mode to check JSON syntax. Common errors include missing commas, unmatched brackets, improper quotes, and trailing commas. Many IDEs also provide real-time JSON validation.
Can JSON handle dates?
JSON doesn't have a native date type. Dates are typically represented as ISO 8601 strings ("2023-12-01T10:30:00Z") or Unix timestamps, then parsed back to date objects in your application.
What's the maximum size for JSON?
JSON itself has no size limit, but practical limits depend on the parser, available memory, and transmission method. Most web servers accept JSON payloads up to several megabytes by default.
Technical Specifications
| Specification | Details |
|---|---|
| MIME Type | application/json |
| File Extension | .json |
| Encoding | UTF-8 (recommended) |
| Standards | RFC 7159, ECMA-404 |
| Data Types | String, Number, Boolean, Null, Object, Array |
Best Practices
- Use consistent naming: Choose camelCase or snake_case and stick to it.
- Keep it flat: Avoid deeply nested structures when possible.
- Validate data: Always validate JSON before processing.
- Handle errors gracefully: Implement proper error handling for parsing failures.
- Use compression: Enable gzip compression for large JSON responses.
- Consider JSON Schema: Define and validate data structure with JSON Schema.
- Escape special characters: Properly escape quotes and control characters in strings.