Skip to content

Instantly share code, notes, and snippets.

@miztizm
Created December 5, 2025 14:06
Show Gist options
  • Select an option

  • Save miztizm/a44912eea4e29201474b939269315b3f to your computer and use it in GitHub Desktop.

Select an option

Save miztizm/a44912eea4e29201474b939269315b3f to your computer and use it in GitHub Desktop.
SimpleStringify - Object to JSON converter
/**
* SimpleStringify - Convert objects to JSON while filtering out complex types
*
* @param {Object} object - The object to stringify
* @param {Object} options - Configuration options
* @param {Boolean} options.includeNulls - Include null values (default: true)
* @param {Boolean} options.includeUndefined - Include undefined values (default: false)
* @param {Number} options.spaces - Number of spaces for indentation (default: 2)
* @returns {String} Cleaned JSON string representation of the object
*/
function simpleStringify(object, options = {}) {
// Validate input
if (object === null || object === undefined) {
return JSON.stringify(object);
}
if (typeof object !== 'object' || Array.isArray(object)) {
return JSON.stringify(object);
}
const {
includeNulls = true,
includeUndefined = false,
spaces = 2
} = options;
const simpleObject = {};
for (const prop in object) {
// Skip inherited properties
if (!object.hasOwnProperty(prop)) {
continue;
}
const value = object[prop];
const type = typeof value;
// Skip functions
if (type === 'function') {
continue;
}
// Skip complex objects and arrays
if (type === 'object') {
// Optionally include null values
if (value === null && !includeNulls) {
continue;
}
if (value === null) {
simpleObject[prop] = null;
}
// Skip other objects and arrays
continue;
}
// Skip undefined if not requested
if (value === undefined && !includeUndefined) {
continue;
}
// Include primitives: string, number, boolean, undefined
simpleObject[prop] = value;
}
return JSON.stringify(simpleObject, null, spaces);
}
// Example usage:
// const user = { name: 'John', age: 30, email: '[email protected]', callback: () => {}, metadata: { id: 1 } };
// console.log(simpleStringify(user));
// Output: { "name": "John", "age": 30, "email": "[email protected]" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment