Skip to content

Instantly share code, notes, and snippets.

@Daymannovaes
Created March 8, 2018 15:52
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 Daymannovaes/10af1025b188fe4dd58aa0b1ebe8d83a to your computer and use it in GitHub Desktop.
Save Daymannovaes/10af1025b188fe4dd58aa0b1ebe8d83a to your computer and use it in GitHub Desktop.
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