npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

json-sanatizer

v1.0.1

Published

A lightweight, robust JSON sanitizer for safe data processing.

Downloads

16

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 sanitize
  • options?: SanitizeOptions - Configuration options (optional)

Returns: Sanitized data

sanitizeValue(value, options?)

Lower-level function to sanitize a single value.

Parameters:

  • value: unknown - The value to sanitize
  • options?: 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__
  • prototype
  • constructor
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

  1. Always sanitize user input before processing or storing
  2. Use strict mode (strictSafeKeys: true) for untrusted data
  3. Customize options based on your use case
  4. Sanitize before validation to ensure clean data structure
  5. 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