Skip to content

Instantly share code, notes, and snippets.

@wkei
Created December 20, 2018 06:43
Show Gist options
  • Save wkei/bf8faca0da2eb2fd73e4ff68b66db503 to your computer and use it in GitHub Desktop.
Save wkei/bf8faca0da2eb2fd73e4ff68b66db503 to your computer and use it in GitHub Desktop.
JSON.stringify
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