Created
September 12, 2019 20:38
-
-
Save verdi327/65b0b18ac7d9c01c1ac2088195ee31c2 to your computer and use it in GitHub Desktop.
encode-json
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(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