Skip to content

Instantly share code, notes, and snippets.

@amatiasq
Created July 18, 2017 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amatiasq/c3477f1f20c793f2917958e2af5e7d83 to your computer and use it in GitHub Desktop.
Save amatiasq/c3477f1f20c793f2917958e2af5e7d83 to your computer and use it in GitHub Desktop.
A custom JSON stringifier
function stringify(value, indent = '') {
const nextIndent = `${indent} `;
if (isNative(value))
return JSON.stringify(value);
if (Array.isArray(value)) {
if (value.length === 1 && isNative(value[0]))
return JSON.stringify(value);
const content = value
.map(entry => stringify(entry, nextIndent))
.map(entry => typeof entry === 'undefined' ? null : entry)
.join(`,\n${nextIndent}`);
return `[\n${nextIndent}${content}\n${indent}]`;
}
if (typeof value !== 'object')
return;
const keys = Object.keys(value);
// if (keys.length === 1)
// return JSON.stringify(value);
const content = keys
.map(key => stringify(value[key], nextIndent))
.filter(value => typeof value !== 'undefined')
.map((value, index) => `"${keys[index]}": ${value}`)
.join(`,\n${nextIndent}`);
return `{\n${nextIndent}${content}\n${indent}}`;
}
function isNative(value) {
const type = typeof value;
return type === 'string' || type === 'number' || type === 'boolean';
}
@amatiasq
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment