🔐Encoding & Escaping
JSON String Escaping
Properly escape strings for JSON format compliance
Explanation
JSON requires escaping of special characters like quotes, backslashes, and control characters.
Examples
Escape quotes
Input
He said "Hello"
Output
He said \"Hello\"
Escape backslash
Input
C:\Users\John
Output
C:\\Users\\John
Code Examples
JavaScript
// Best practice: Use JSON.stringify
const obj = {
name: 'John "The King"',
path: 'C:\\Users\\John',
message: 'Line 1\nLine 2\tTabbed'
};
const json = JSON.stringify(obj);
console.log(json);
// {"name":"John \"The King\"","path":"C:\\Users\\John",...}
// Pretty print
const prettyJson = JSON.stringify(obj, null, 2);
// Manual escape (rarely needed)
function escapeJsonString(str) {
return str
.replace(/\\/g, '\\\\') // Backslash
.replace(/"/g, '\\"') // Quote
.replace(/\n/g, '\\n') // Newline
.replace(/\r/g, '\\r') // Carriage return
.replace(/\t/g, '\\t') // Tab
.replace(/\b/g, '\\b') // Backspace
.replace(/\f/g, '\\f') // Form feed
.replace(/[\x00-\x1f]/g, c => { // Control chars
return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
});
}
// Unescape JSON string
function unescapeJsonString(str) {
return str
.replace(/\\"/g, '"')
.replace(/\\\\/g, '\\')
.replace(/\\n/g, '\n')
.replace(/\\r/g, '\r')
.replace(/\\t/g, '\t')
.replace(/\\u([0-9a-fA-F]{4})/g, (match, hex) => {
return String.fromCharCode(parseInt(hex, 16));
});
}
// Parse with error handling
function safeJsonParse(str) {
try {
return JSON.parse(str);
} catch (error) {
console.error('Invalid JSON:', error.message);
return null;
}
}
// Stringify with circular reference handling
function safeJsonStringify(obj) {
const seen = new WeakSet();
return JSON.stringify(obj, (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular]';
}
seen.add(value);
}
return value;
});
} Python
import json
# Encode to JSON (handles escaping automatically)
data = {
'name': 'John "The King"',
'path': 'C:\\Users\\John',
'message': 'Line 1\nLine 2\tTabbed'
}
json_str = json.dumps(data)
print(json_str)
# Pretty print
pretty_json = json.dumps(data, indent=2)
# Decode from JSON
parsed = json.loads(json_str)
# Custom JSON encoder for non-serializable types
from datetime import datetime
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
data_with_date = {'timestamp': datetime.now()}
json.dumps(data_with_date, cls=DateTimeEncoder)
# Handle encoding errors
json.dumps(data, ensure_ascii=False) # Allow Unicode
json.dumps(data, ensure_ascii=True) # Escape UnicodeTry it Now
💡 Tips
- Always use JSON.stringify() instead of manual escaping
- JSON requires double quotes, not single
- Escape: \, ", \n, \r, \t, \b, \f
- Control characters (\x00-\x1f) need Unicode escaping
- Handle circular references in complex objects
- Use try-catch for JSON.parse
- Pretty print with indent parameter
⚠️ Common Pitfalls
- Single quotes are not valid JSON
- Trailing commas break JSON
- undefined, functions, symbols are omitted
- NaN and Infinity become null
- Circular references throw errors
- BigInt values cannot be serialized
- Date objects become strings