Created
March 8, 2018 15:52
-
-
Save Daymannovaes/10af1025b188fe4dd58aa0b1ebe8d83a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 prettyJson(object, indent = 4, stack = []) { | |
stack.push(object); | |
let result = "{\n"; | |
let indentString = (new Array(indent+1)).join(" "); | |
let indentEnd = (new Array(indent-3)).join(" "); | |
let keys = Object.keys(object); | |
keys.forEach((key, i) => { | |
let value = object[key]; | |
result += indentString + `"${key}": `; | |
if(typeof value === "object") result += stack.includes(value) ? "[Circular Object]" : prettyJson(value, indent + 4, stack); | |
else if(typeof value === "string") result += `"${value}"`; | |
else result += value; | |
result += i === (keys.length - 1) ? "\n" : ",\n"; | |
}); | |
return result + indentEnd + "}" | |
} | |
// use as prettyJson({ a: 1, b: 2, c: '3', nested: { d: false, e: 4, j: 'string' } }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment