Custom JSON Formatter
What is Custom JSON Formatting?
Custom JSON Formatter is a powerful tool for transforming JSON data into customized string formats with full control over formatting, indentation, line breaks, and delimiter characters. Unlike standard JSON stringification, this tool allows you to create strings that match specific output requirements, coding styles, or integration needs.
Understanding the Conversion
This converter transforms structured JSON data into formatted text strings with complete control over every aspect of the output format. You can customize indentation, line breaks, key wrapping, and value wrapping to create strings that fit your exact specifications.
Custom JSON Formatter vs Standard JSON.stringify()
Aspect | Standard JSON.stringify() | Custom JSON Formatter |
---|---|---|
Indentation Control | Fixed spaces or tabs | Customizable amount and character |
Line Breaks | Single newline between elements | Configurable multiple line breaks |
Key Formatting | Always double quotes | Customizable wrapping characters |
Value Formatting | Type-specific formatting | Customizable wrapping for all values |
Output Style | Standard JSON format | Any custom string format |
Use Cases | Data serialization | Code generation, templates, custom formats |
Configuration Options
1. Line Breaks (Newline)
Controls how many line breaks to insert between elements.
// Configuration: enter = 1 (default)
{
"name": "John",
"age": 30
}
// Configuration: enter = 2 (double spacing)
{
"name": "John",
"age": 30
}
// Configuration: enter = 0 (compact)
{"name": "John","age": 30}
2. Indentation Amount
Specifies how many indentation characters to use for each nesting level.
// Configuration: fillAmount = 2
{
"user": {
"name": "John"
}
}
// Configuration: fillAmount = 4
{
"user": {
"name": "John"
}
}
// Configuration: fillAmount = 1
{
"user": {
"name": "John"
}
}
3. Indentation Character
Defines what character to use for indentation (spaces, tabs, custom characters).
// Configuration: fillChar = " " (space)
{
"name": "John"
}
// Configuration: fillChar = "\t" (tab)
{
"name": "John"
}
// Configuration: fillChar = "-" (custom)
{
--"name": "John"
}
4. Key Wrapping
Specifies what characters to wrap object keys with.
// Configuration: keyWrap = '"' (double quotes - default)
{
"name": "John",
"age": 30
}
// Configuration: keyWrap = "'" (single quotes)
{
'name': 'John',
'age': 30
}
// Configuration: keyWrap = "" (no quotes)
{
name: "John",
age: 30
}
// Configuration: keyWrap = "`" (backticks)
{
`name`: "John",
`age`: 30
}
5. Value Wrapping
Defines what characters to wrap values with (affects all values regardless of type).
// Configuration: valueWrap = '"' (double quotes)
{
"name": "John",
"age": "30",
"active": "true"
}
// Configuration: valueWrap = "'" (single quotes)
{
"name": 'John',
"age": '30',
"active": 'true'
}
// Configuration: valueWrap = "" (no wrapping)
{
"name": John,
"age": 30,
"active": true
}
Practical Use Cases
1. JavaScript Object Generation
Generate JavaScript object literals from JSON data:
Input JSON:
{
"apiUrl": "https://api.example.com",
"timeout": 5000,
"retries": 3
}
Configuration:
- Key Wrap: "" (no quotes)
- Value Wrap: "" (no wrapping for primitives)
- Indentation: 2 spaces
Output:
{
apiUrl: "https://api.example.com",
timeout: 5000,
retries: 3
}
2. Python Dictionary Format
Convert JSON to Python dictionary syntax:
Input JSON:
{
"name": "John Doe",
"scores": [95, 87, 92],
"active": true
}
Configuration:
- Key Wrap: "'" (single quotes)
- Value Wrap: "'" (single quotes for strings)
- Indentation: 4 spaces
Output:
{
'name': 'John Doe',
'scores': [95, 87, 92],
'active': True
}
3. Configuration File Templates
Generate configuration files with custom formatting:
Input JSON:
{
"database": {
"host": "localhost",
"port": 5432,
"name": "myapp"
},
"cache": {
"enabled": true,
"ttl": 3600
}
}
Configuration:
- Line Breaks: 2
- Indentation: 4 spaces
- Key Wrap: "" (no quotes)
- Value Wrap: '"'
Output:
{
database: {
host: "localhost",
port: "5432",
name: "myapp"
},
cache: {
enabled: "true",
ttl: "3600"
}
}
4. Code Template Generation
Create code templates from JSON specifications:
Input JSON:
{
"className": "UserService",
"methods": ["create", "update", "delete"],
"properties": {
"baseUrl": "/api/users",
"timeout": 30000
}
}
Configuration:
- Key Wrap: "" (no quotes for property names)
- Value Wrap: "'" (single quotes for strings)
- Indentation: 2 spaces
Output:
{
className: 'UserService',
methods: ['create', 'update', 'delete'],
properties: {
baseUrl: '/api/users',
timeout: '30000'
}
}
Advanced Examples
Example 1: SQL Insert Statement Template
Input JSON:
{
"users": [
{"id": 1, "name": "Alice", "email": "[email protected]"},
{"id": 2, "name": "Bob", "email": "[email protected]"}
]
}
Configuration for SQL-like format:
- Key Wrap: "`" (backticks for SQL column names)
- Value Wrap: "'" (single quotes for SQL strings)
- Indentation: 4 spaces
- Line Breaks: 1
Output:
{
`users`: [
{
`id`: '1',
`name`: 'Alice',
`email`: '[email protected]'
},
{
`id`: '2',
`name`: 'Bob',
`email`: '[email protected]'
}
]
}
Example 2: YAML-like Format
Input JSON:
{
"server": {
"host": "localhost",
"port": 8080,
"ssl": false
},
"database": {
"driver": "postgresql",
"url": "postgresql://localhost:5432/mydb"
}
}
Configuration:
- Key Wrap: "" (no quotes)
- Value Wrap: "" (no value wrapping)
- Indentation: 2 spaces
- Line Breaks: 1
Output:
{
server: {
host: localhost,
port: 8080,
ssl: false
},
database: {
driver: postgresql,
url: postgresql://localhost:5432/mydb
}
}
Example 3: Custom Template Format
Input JSON:
{
"component": "Button",
"props": {
"variant": "primary",
"size": "large",
"disabled": false
},
"children": "Click me"
}
Configuration for template format:
- Key Wrap: "" (no quotes)
- Value Wrap: "${}" (template literal format)
- Indentation: 3 spaces
- Line Breaks: 2
Output:
{
component: ${Button},
props: {
variant: ${primary},
size: ${large},
disabled: ${false}
},
children: ${Click me}
}
Configuration Combinations
Web Development Formats
JavaScript ES6 Object
// Configuration: keyWrap="", valueWrap="", fillAmount=2
{
apiEndpoint: "https://api.example.com",
apiKey: process.env.API_KEY,
timeout: 5000
}
React Props Format
// Configuration: keyWrap="", valueWrap={}, fillAmount=2
{
title: {"Welcome"},
isVisible: {true},
onClick: {handleClick}
}
JSON with Comments Style
// Configuration: keyWrap='"', valueWrap='"', fillAmount=2, enter=1
{
"// Configuration": "Application settings",
"debug": "true",
"version": "1.0.0"
}
Data Format Conversions
CSV Header Generation
// Configuration: keyWrap="", valueWrap='"', fillAmount=0, enter=0
{name:"John",age:"30",city:"New York"}
Environment Variables Format
# Configuration: keyWrap="", valueWrap="", custom processing
API_URL=https://api.example.com
DEBUG_MODE=true
PORT=3000
INI File Format
# Configuration: keyWrap="", valueWrap="", custom formatting
[database]
host=localhost
port=5432
name=myapp
Best Practices
1. Choose Appropriate Wrapping
// For JavaScript objects - no key quotes needed
{
property: "value",
method: function() {}
}
// For JSON data exchange - always use quotes
{
"property": "value",
"timestamp": "2024-01-15T10:30:00Z"
}
2. Consistent Indentation
// Good: Consistent 2-space indentation
{
user: {
profile: {
name: "John"
}
}
}
// Avoid: Mixed indentation
{
user: {
profile: {
name: "John"
}
}
}
3. Appropriate Line Spacing
// For compact output: enter = 0
{"name":"John","age":30}
// For readable code: enter = 1
{
"name": "John",
"age": 30
}
// For documentation: enter = 2
{
"name": "John",
"age": 30
}
4. Context-Aware Formatting
// API responses: Standard JSON
{
"data": {"user": "John"},
"status": "success"
}
// Configuration files: Readable format
{
database: {
host: "localhost",
port: 5432
}
}
// Code generation: Language-specific format
const config = {
apiUrl: process.env.API_URL,
timeout: 5000
};
Common Output Formats
1. Programming Language Objects
JavaScript
// keyWrap="", valueWrap="" (for primitives)
const config = {
apiUrl: "https://api.example.com",
retries: 3,
timeout: 5000
};
Python
# keyWrap="'", valueWrap="'" (for strings)
config = {
'api_url': 'https://api.example.com',
'retries': 3,
'timeout': 5000
}
PHP
// keyWrap="'", valueWrap="'"
$config = array(
'api_url' => 'https://api.example.com',
'retries' => 3,
'timeout' => 5000
);
2. Configuration File Formats
TOML-like
# keyWrap="", valueWrap=""
[database]
host = "localhost"
port = 5432
name = "myapp"
Properties File
# keyWrap="", valueWrap="", custom separator
database.host=localhost
database.port=5432
database.name=myapp
3. Template Formats
Mustache Template
# keyWrap="", valueWrap="{{|}}"
{
name: {{name}},
email: {{email}},
active: {{active}}
}
Handlebars Template
# keyWrap="", valueWrap="{{|}}"
{
title: {{title}},
content: {{content}},
author: {{author.name}}
}
Integration Examples
1. Code Generation Workflow
// Step 1: Define data model
const model = {
"entity": "User",
"fields": [
{"name": "id", "type": "number"},
{"name": "email", "type": "string"},
{"name": "active", "type": "boolean"}
]
};
// Step 2: Convert with appropriate formatting
// Configuration: keyWrap="", valueWrap="" for JS
const jsObject = convertToString(model);
// Step 3: Use in code template
const template = `
class ${jsObject.entity} {
constructor(data) {
${jsObject.fields.map(f => `this.${f.name} = data.${f.name};`).join('\n ')}
}
}
`;
2. Configuration File Generation
// Environment-specific configs
const devConfig = {
"database": {"host": "localhost", "port": 5432},
"redis": {"host": "localhost", "port": 6379},
"debug": true
};
// Convert for different environments
const jsConfig = convertToString(devConfig, {
keyWrap: "",
valueWrap: "",
fillAmount: 2
});
const dockerConfig = convertToString(devConfig, {
keyWrap: "",
valueWrap: "${|}", // Docker environment variables
fillAmount: 2
});
3. API Documentation Generation
// API endpoint specification
const apiSpec = {
"endpoint": "/api/users",
"method": "POST",
"body": {
"name": "string",
"email": "string",
"age": "number"
}
};
// Convert for documentation
const docFormat = convertToString(apiSpec, {
keyWrap: '"',
valueWrap: '"',
fillAmount: 2,
enter: 1
});
Advanced Customization
1. Custom Separators
// Instead of commas, use semicolons
{
name: "John";
age: 30;
city: "New York"
}
2. Special Character Handling
// Escape special characters in values
{
"message": "He said \"Hello, World!\"",
"path": "C:\\Users\\John\\Documents",
"regex": "/^[a-zA-Z0-9]+$/"
}
3. Conditional Formatting
// Different formatting based on data type
{
stringValue: "wrapped in quotes",
numberValue: 42,
booleanValue: true,
nullValue: null
}
Performance Considerations
1. Large Objects
// For large objects, consider streaming or chunking
const largeData = {
users: new Array(10000).fill(null).map((_, i) => ({
id: i,
name: `User ${i}`,
email: `user${i}@example.com`
}))
};
// Process in chunks to avoid memory issues
function processLargeObject(data, chunkSize = 1000) {
// Implementation for chunked processing
}
2. Real-time Conversion
// Debounce user input for real-time conversion
function debouncedConvert(jsonInput, config) {
clearTimeout(conversionTimer);
conversionTimer = setTimeout(() => {
const result = convertToString(jsonInput, config);
updateOutput(result);
}, 300);
}
Error Handling
1. Invalid JSON Input
// Handle malformed JSON gracefully
try {
const parsed = JSON.parse(userInput);
const converted = convertToString(parsed, config);
return { success: true, result: converted };
} catch (error) {
return {
success: false,
error: "Invalid JSON format",
details: error.message
};
}
2. Configuration Validation
// Validate configuration options
function validateConfig(config) {
const errors = [];
if (config.fillAmount < 0) {
errors.push("Indentation amount must be non-negative");
}
if (config.enter < 0) {
errors.push("Line breaks must be non-negative");
}
return errors;
}
Conclusion
Custom JSON Formatter is a powerful tool for:
- Code Generation - Creating language-specific object literals
- Configuration Management - Converting between different config formats
- Template Creation - Generating templates with placeholder syntax
- Data Format Conversion - Adapting JSON for specific system requirements
- Documentation - Creating readable examples and specifications
Key benefits:
- Full Control over output formatting
- Language Agnostic - works for any target format
- Template Support - placeholder and variable substitution
- Readable Output - customizable spacing and indentation
- Integration Ready - perfect for build tools and code generators
The flexibility of customizable key wrapping, value wrapping, indentation, and line breaks makes this tool essential for developers working with data transformation, code generation, and system integration tasks.