Complete guide to secure JSON processing, vulnerability prevention, and privacy-first development practices for modern applications.
JSON processing can introduce several security vulnerabilities if not handled properly. Understanding these risks is crucial for building secure applications.
Malicious JSON payloads can contain executable code or manipulate application logic through crafted data structures.
Unsanitized JSON data displayed in web applications can execute malicious scripts in user browsers.
JavaScript JSON parsing can modify object prototypes, leading to property injection and security bypasses.
Extremely large JSON files can consume excessive memory and processing power, causing denial of service.
Uploading sensitive JSON to online tools exposes confidential data to third parties and potential breaches.
Using eval() to parse JSON enables arbitrary code execution and complete system compromise.
Never use eval()
to parse JSON data. Always use JSON.parse()
with proper error handling and validation.
// ✅ SECURE: Proper JSON parsing
function secureJSONParse(jsonString) {
try {
// Validate input is string
if (typeof jsonString !== 'string') {
throw new Error('Input must be a string');
}
// Check size limits (e.g., 10MB)
if (jsonString.length > 10 * 1024 * 1024) {
throw new Error('JSON payload too large');
}
// Parse with JSON.parse()
const parsed = JSON.parse(jsonString);
// Additional validation
if (parsed === null) {
throw new Error('JSON cannot be null');
}
return parsed;
} catch (error) {
console.error('JSON parsing failed:', error.message);
return null;
}
}
// ❌ INSECURE: Never do this
function insecureJSONParse(jsonString) {
return eval('(' + jsonString + ')'); // DANGEROUS!
}
// ✅ Validate JSON structure
function validateJSONStructure(obj) {
// Check for prototype pollution attempts
const dangerousKeys = ['__proto__', 'constructor', 'prototype'];
function checkObject(obj, path = '') {
if (obj === null || typeof obj !== 'object') {
return true;
}
for (const key in obj) {
if (dangerousKeys.includes(key)) {
throw new Error(`Dangerous key detected: ${key} at ${path}`);
}
if (obj.hasOwnProperty(key)) {
checkObject(obj[key], path + '.' + key);
}
}
return true;
}
return checkObject(obj);
}
// ✅ Sanitize JSON values for display
function sanitizeJSONForDisplay(value) {
if (typeof value === 'string') {
return value
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
return value;
}
Implement multiple layers of validation: input validation, structure checking, size limits, and output sanitization.
// ✅ JSON parser with built-in protections
class SecureJSONParser {
constructor(options = {}) {
this.maxSize = options.maxSize || 10 * 1024 * 1024; // 10MB
this.maxDepth = options.maxDepth || 100;
this.maxKeys = options.maxKeys || 10000;
}
parse(jsonString) {
// Size check
if (jsonString.length > this.maxSize) {
throw new Error('JSON payload exceeds size limit');
}
const parsed = JSON.parse(jsonString);
// Depth and complexity check
this.validateComplexity(parsed, 0);
return parsed;
}
validateComplexity(obj, depth = 0, keyCount = 0) {
if (depth > this.maxDepth) {
throw new Error('JSON depth exceeds limit');
}
if (keyCount > this.maxKeys) {
throw new Error('JSON key count exceeds limit');
}
if (Array.isArray(obj)) {
obj.forEach(item =>
this.validateComplexity(item, depth + 1, keyCount)
);
} else if (obj !== null && typeof obj === 'object') {
const keys = Object.keys(obj);
keyCount += keys.length;
keys.forEach(key =>
this.validateComplexity(obj[key], depth + 1, keyCount)
);
}
}
}
Cross-Site Scripting (XSS) attacks through JSON data are a serious threat. Here's how to prevent them effectively.
// ✅ SECURE: Use textContent for JSON display
function displayJSONSecurely(jsonData, element) {
// Convert to formatted JSON string
const jsonString = JSON.stringify(jsonData, null, 2);
// Use textContent to prevent script execution
element.textContent = jsonString;
// Alternative: Use innerHTML with proper escaping
// element.innerHTML = escapeHTML(jsonString);
}
// ❌ INSECURE: Direct innerHTML assignment
function displayJSONUnsafely(jsonData, element) {
const jsonString = JSON.stringify(jsonData, null, 2);
element.innerHTML = jsonString; // DANGEROUS!
}
// ✅ HTML escaping function
function escapeHTML(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
<meta http-equiv="Content-Security-Policy"
content="default-src 'self';
script-src 'self' 'unsafe-inline';
style-src 'self' 'unsafe-inline';
img-src 'self' data:;">
<meta http-equiv="Content-Security-Policy"
content="default-src 'self';
script-src 'self';
style-src 'self';
object-src 'none';
base-uri 'self';">
// ✅ Comprehensive JSON sanitization
class JSONSanitizer {
static sanitizeValue(value, depth = 0) {
// Prevent deep recursion DoS
if (depth > 50) {
return '[MAX_DEPTH_EXCEEDED]';
}
if (typeof value === 'string') {
return this.sanitizeString(value);
} else if (Array.isArray(value)) {
return value.map(item => this.sanitizeValue(item, depth + 1));
} else if (value !== null && typeof value === 'object') {
const sanitized = {};
Object.keys(value).forEach(key => {
const safeKey = this.sanitizeString(key);
sanitized[safeKey] = this.sanitizeValue(value[key], depth + 1);
});
return sanitized;
}
return value;
}
static sanitizeString(str) {
return str
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/\//g, '/')
.replace(/\\/g, '\')
.replace(/`/g, '`');
}
static sanitizeForDisplay(jsonObj) {
const sanitized = this.sanitizeValue(jsonObj);
return JSON.stringify(sanitized, null, 2);
}
}
Always sanitize JSON data before displaying it in the DOM, even if it comes from trusted sources. Assume all input is potentially malicious.
Protecting user privacy should be the foundation of any JSON processing tool or application.
Process JSON data entirely in the browser without sending to external servers
Never collect, store, or transmit user JSON data to analytics or tracking services
Enable full functionality without internet connection to ensure complete privacy
Clear sensitive data from memory immediately after processing
Not all JSON tools are created equal. Here's how to evaluate the security and privacy of different JSON processing options:
Security Feature | Client-Side Tools | Online Validators | Better JSON Viewer |
---|---|---|---|
Data Privacy | ✅ Private | ❌ Exposed | ✅ 100% Private |
No Data Upload | ✅ Local Only | ❌ Uploads Data | ✅ Local Processing |
Works Offline | ✅ Yes | ❌ Requires Internet | ✅ Full Offline |
XSS Protection | ⚠️ Depends | ⚠️ Varies | ✅ Built-in |
Size Limits | ⚠️ Browser Only | ❌ Server Limits | ✅ Configurable |
// ✅ Client-side processing flow
1. JSON data stays in browser memory
2. Processing happens locally using JavaScript
3. Results displayed immediately
4. No network requests for data processing
5. Sensitive data never transmitted
// ❌ Server-side processing risks
1. JSON uploaded to external server
2. Data temporarily stored on third-party systems
3. Potential for data logging/tracking
4. Network transmission vulnerabilities
5. Server-side processing delays
JSON.parse()
instead of eval()
Use Better JSON Viewer for completely private, secure JSON processing. All data stays in your browser with zero tracking or data collection.
Try Secure JSON Viewer →This guide helps developers build secure, privacy-first JSON processing applications.
Last updated: January 14, 2025 • © 2025 Better JSON Viewer