json-sanatizer
v1.0.1
Published
A lightweight, robust JSON sanitizer for safe data processing.
Downloads
16
Maintainers
Readme
🧹 JSON Sanitizer
A lightweight, robust JSON sanitizer for safe data processing in both frontend and backend applications.
📦 What It Does
json-sanitizer safely cleans JSON objects before storing, processing, or sending to an API. It helps prevent:
- ✅ Polluted JSON structures
- ✅ Wrong data types
- ✅ Unnecessary whitespace
- ✅ Unsafe keys
- ✅ Prototype pollution attacks
✨ Features
- Remove unnecessary fields - null, undefined, empty strings, empty objects
- Trim text fields - automatic string trimming and space collapsing
- Auto-convert numeric strings -
"45"→45,"12.34"→12.34 - Prevent prototype pollution - blocks
__proto__,prototype,constructor - Deep recursive cleaning - handles nested objects and arrays
- Fully configurable - enable/disable any feature
- TypeScript support - full type definitions included
- Zero dependencies - lightweight and secure
- ESM + CommonJS - works everywhere
📥 Installation
npm install json-sanitizer🚀 Quick Start
import { sanitizeJSON } from 'json-sanitizer';
const dirty = {
name: ' John ',
age: '25',
empty: '',
x: null,
__proto__: 'hack',
};
const clean = sanitizeJSON(dirty);
console.log(clean);
// Output: { name: "John", age: 25 }📖 Usage Examples
Basic Example
import { sanitizeJSON } from 'json-sanitizer';
const input = {
username: ' alice ',
score: '100',
notes: null,
metadata: {},
};
const output = sanitizeJSON(input);
// { username: "alice", score: 100 }Nested Objects and Arrays
const input = {
user: {
name: ' Bob ',
details: {
age: '30',
tags: [null, ' admin ', ' user ', {}],
},
},
};
const output = sanitizeJSON(input);
// {
// user: {
// name: "Bob",
// details: {
// age: 30,
// tags: ["admin", "user"]
// }
// }
// }Custom Options
const input = {
name: ' John ',
email: '',
age: '25',
};
const output = sanitizeJSON(input, {
removeEmptyStrings: false,
convertNumberStrings: false,
});
// { name: "John", email: "", age: "25" }Preventing Prototype Pollution
const malicious = JSON.parse(
'{"__proto__": {"isAdmin": true}, "name": "hacker"}'
);
const safe = sanitizeJSON(malicious);
// { name: "hacker" }
// __proto__ is completely removed🔧 API Reference
sanitizeJSON(data, options?)
Main function to sanitize any JSON-compatible data.
Parameters:
data: unknown- The data to sanitizeoptions?: SanitizeOptions- Configuration options (optional)
Returns: Sanitized data
sanitizeValue(value, options?)
Lower-level function to sanitize a single value.
Parameters:
value: unknown- The value to sanitizeoptions?: SanitizeOptions- Configuration options (optional)
Returns: Sanitized value
isNumericString(str)
Check if a string represents a valid number.
Parameters:
str: string- The string to check
Returns: boolean
isSafeKey(key)
Check if an object key is safe (not __proto__, prototype, or constructor).
Parameters:
key: string- The key to check
Returns: boolean
⚙️ Configuration Options
| Option | Type | Default | Description |
| ---------------------- | --------- | ------- | ----------------------------------------------- |
| removeNull | boolean | true | Remove properties with null values |
| removeUndefined | boolean | true | Remove properties with undefined values |
| removeEmptyStrings | boolean | true | Remove properties with empty string values |
| removeEmptyObjects | boolean | true | Remove properties with empty object values {} |
| trimStrings | boolean | true | Trim whitespace from strings |
| collapseSpaces | boolean | true | Convert multiple spaces to single space |
| convertNumberStrings | boolean | true | Convert numeric strings to numbers |
| strictSafeKeys | boolean | true | Block unsafe keys like __proto__ |
Default Configuration
{
removeNull: true,
removeUndefined: true,
removeEmptyStrings: true,
removeEmptyObjects: true,
trimStrings: true,
collapseSpaces: true,
convertNumberStrings: true,
strictSafeKeys: true
}🛡️ Security Features
Prototype Pollution Prevention
The sanitizer automatically blocks dangerous keys:
__proto__prototypeconstructor
const attack = {
__proto__: { isAdmin: true },
constructor: { polluted: true },
prototype: { hacked: true },
safe: 'data',
};
const clean = sanitizeJSON(attack);
// { safe: "data" }Immutability
The original object is never modified. A new object is always returned:
const original = { name: ' test ' };
const cleaned = sanitizeJSON(original);
console.log(original); // { name: " test " }
console.log(cleaned); // { name: "test" }Plain Objects Only
By default, only plain objects are deeply sanitized. Class instances are preserved:
class User {
constructor(public name: string) {}
}
const user = new User(' Alice ');
const result = sanitizeJSON({ user });
// The User instance is preserved, not deeply sanitized💡 Common Use Cases
1. API Request Sanitization
import { sanitizeJSON } from 'json-sanitizer';
async function createUser(userData) {
const clean = sanitizeJSON(userData);
return fetch('/api/users', {
method: 'POST',
body: JSON.stringify(clean),
});
}2. Form Data Processing
function handleFormSubmit(formData) {
const sanitized = sanitizeJSON({
name: formData.get('name'),
email: formData.get('email'),
age: formData.get('age'),
});
// All strings trimmed, age converted to number
saveToDatabase(sanitized);
}3. Database Storage
import { sanitizeJSON } from 'json-sanitizer';
async function saveDocument(doc) {
const clean = sanitizeJSON(doc, {
removeNull: true,
removeEmptyObjects: true,
});
await db.collection('docs').insertOne(clean);
}4. Configuration Files
import { sanitizeJSON } from 'json-sanitizer';
import fs from 'fs';
const config = JSON.parse(fs.readFileSync('config.json', 'utf-8'));
const cleanConfig = sanitizeJSON(config);5. User Input Validation
function processUserInput(input) {
const sanitized = sanitizeJSON(input, {
trimStrings: true,
strictSafeKeys: true,
removeEmptyStrings: true,
});
return sanitized;
}🔍 Best Practices
- Always sanitize user input before processing or storing
- Use strict mode (
strictSafeKeys: true) for untrusted data - Customize options based on your use case
- Sanitize before validation to ensure clean data structure
- Don't rely solely on sanitization - use proper validation too
📝 TypeScript Support
Full TypeScript support with type definitions:
import { sanitizeJSON, SanitizeOptions } from 'json-sanitizer';
interface User {
name: string;
age: number;
}
const options: SanitizeOptions = {
trimStrings: true,
convertNumberStrings: true,
};
const user = sanitizeJSON<User>({ name: ' Alice ', age: '30' }, options);
// user is typed as User🧪 Testing
The package includes comprehensive tests covering:
- ✅ String trimming and space collapsing
- ✅ Null/undefined removal
- ✅ Empty string/object removal
- ✅ Number string conversion
- ✅ Array sanitization
- ✅ Deep nested object sanitization
- ✅ Prototype pollution prevention
- ✅ All configuration options
Run tests:
npm test📦 Package Size
- Minified: ~1.5KB
- Gzipped: ~0.7KB
- Zero dependencies
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📄 License
MIT License - see LICENSE file for details
🔗 Links
📊 Changelog
See CHANGELOG.md for version history.
Made with ❤️ for safer JSON processing
