Created
July 18, 2017 16:37
-
-
Save amatiasq/c3477f1f20c793f2917958e2af5e7d83 to your computer and use it in GitHub Desktop.
A custom JSON stringifier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Moved to https://github.com/amatiasq/snippets/blob/master/stringify.js