Skip to content

Instantly share code, notes, and snippets.

@mrgrain
Created February 6, 2023 11:28
Show Gist options
  • Save mrgrain/a61408a4e8dd2006be5000a6523bf28e to your computer and use it in GitHub Desktop.
Save mrgrain/a61408a4e8dd2006be5000a6523bf28e to your computer and use it in GitHub Desktop.
stringify javascript values with support for Symbols that will be rendered as is
function stringify(data, indentation = 2) {
if (typeof indentation === "number") {
return doStringify(data, 0, " ".repeat(indentation))
}
return doStringify(data, 0, indentation)
}
function doStringify(data, level = 0, idt = " ") {
if (typeof data === "symbol") {
return data.description;
}
if (Array.isArray(data)) {
return "[" + "\n"
+ data.map(val => idt.repeat(level + 1) + doStringify(val, level + 1, idt) + ",").join('\n')
+ "\n" + idt.repeat(level) + "]"
}
if (data && typeof data === 'object') {
return "{" + "\n"
+ Object.entries(data)
.map(([key, val]) => idt.repeat(level + 1) + JSON.stringify(key) + ": " + doStringify(val, level + 1, idt) + ",")
.join("\n")
+ "\n" + idt.repeat(level) + "}"
}
return JSON.stringify(data);
}
console.log(stringify([1, "string", true, {
a: "b"
}]))
console.log(stringify({
"null": null,
"infinity": Infinity,
"date": Date.now(),
banana: "bread",
"foo": "bar",
"number": 1,
"truth": false,
"array": [1, "string", true, {
a: "b"
}],
"object": {
"a": "b",
sym: Symbol("__dirname"),
func: Symbol("JSON.stringify(1)")
}
}));
@mrgrain
Copy link
Author

mrgrain commented Feb 6, 2023

Output

[
  1,
  "string",
  true,
  {
    "a": "b",
  },
]
{
  "null": null,
  "infinity": null,
  "date": 1675682915616,
  "banana": "bread",
  "foo": "bar",
  "number": 1,
  "truth": false,
  "array": [
    1,
    "string",
    true,
    {
      "a": "b",
    },
  ],
  "object": {
    "a": "b",
    "sym": __dirname,
    "func": JSON.stringify(1),
  },
}

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