Last active
September 27, 2022 03:07
-
-
Save 1oo1/8db0303deca2f2b06066fd78ff63e8be to your computer and use it in GitHub Desktop.
js/ts 简易定制 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
function myJsonify(json: any, level = 0): string { | |
let result = ''; | |
if (Array.isArray(json)) { | |
result += "[\n"; | |
for (const item of json) { | |
for (let i = 0; i < level * 2 + 2; i++) { | |
result += ' '; | |
} | |
result += `${myJsonify(item, level + 1)},\n`; | |
} | |
result = result.substring(0, result.length - 2); | |
result += "\n"; | |
for (let i = 0; i < level * 2; i++) { | |
result += ' '; | |
} | |
result += "]"; | |
} else if (typeof json === 'object') { | |
result += '{\n'; | |
for (const key in json) { | |
if (Object.prototype.hasOwnProperty.call(json, key)) { | |
for (let i = 0; i < level * 2 + 2; i++) { | |
result += ' '; | |
} | |
const value = json[key]; | |
// 定制 component 字段特殊处理 | |
if (key === 'component') { | |
result += `${key}: () => import('@${value.startsWith('/') ? value : '/' + value}'),\n` | |
} else { | |
result += `${key}: ${myJsonify(value, level + 1)},\n`; | |
} | |
} | |
} | |
result = result.substring(0, result.length - 2); | |
result += '\n'; | |
for (let i = 0; i < level * 2; i++) { | |
result += ' '; | |
} | |
result += "}"; | |
} else if (typeof json === 'string') { | |
result += `'${json}'`; | |
} else { | |
result += `${json}`; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment