Created
December 20, 2018 06:43
-
-
Save wkei/bf8faca0da2eb2fd73e4ff68b66db503 to your computer and use it in GitHub Desktop.
JSON.stringify
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
const json2str = (target) => { | |
switch (typeof target) { | |
case 'number': | |
return isNaN(target) ? 'null' : target.toString() | |
case 'boolean': | |
return target.toString() | |
case 'string': | |
return `"${target}"` | |
case 'object': | |
if (target === null) { | |
// null | |
return 'null' | |
} else if (Array.isArray(target)) { | |
const arr = target | |
.map(item => { | |
const str = json2str(item) | |
return str === undefined ? 'null' : str | |
}) | |
return `[${arr.join(',')}]` | |
} else if (target.toString() === '[object Object]') { | |
const arr = Object.keys(target) | |
.map(key => { | |
const obj = target[key] | |
const str = json2str(obj) | |
return str === undefined ? str : `"${key}":${str}` | |
}) | |
.filter(item => item !== undefined) | |
return `{${arr.join(',')}}` | |
} | |
// map | |
// set | |
return '{}' | |
default: | |
// undefined | |
// function | |
return undefined | |
} | |
} | |
const test = (json) => { | |
if (JSON.stringify(json) === json2str(json)) { | |
console.log('test successfully') | |
} else { | |
console.log('test failure', JSON.stringify(json), json2str(json)) | |
} | |
} | |
test("hello world") | |
test(true) | |
test(false) | |
test(0) | |
test(1) | |
test(null) | |
test(undefined) | |
test(NaN) | |
test(function() {}) | |
test([0, 1]) | |
test({0: 'ha', '1': 'hello' }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment