Skip to content

Instantly share code, notes, and snippets.

@verdi327
Created September 12, 2019 20:38
Show Gist options
  • Save verdi327/65b0b18ac7d9c01c1ac2088195ee31c2 to your computer and use it in GitHub Desktop.
Save verdi327/65b0b18ac7d9c01c1ac2088195ee31c2 to your computer and use it in GitHub Desktop.
encode-json
function stringify(input) {
if (!input) return "null";
if (typeof(input) === 'string') return input;
if (typeof(input) === 'number') return `"${input}"`;
if (Array.isArray(input)) {
let result = [];
input.forEach(value => {
result.push(stringify(value));
});
return `[${result}]`;
}
if (typeof(input) === 'object' && !Array.isArray(input)) {
let temp = {};
for (const [key,value] of Object.entries(input)) {
temp[key] = stringify(value);
}
let result = [];
for (const [key,value] of Object.entries(temp)) {
result.push(`${key}: ${value}`);
}
return `{${result.join(', ')}}`;
}
}
console.log(stringify("abc"));
console.log(stringify(9));
console.log(stringify(null));
console.log(stringify(["abc", 123, null, [5, [6]]]));
console.log(stringify({"foo": 9, "bar": null, "baz": {"cat": 22}}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment