2633. 将对象转换为 JSON 字符串
2025年6月25日小于 1 分钟
2633. 将对象转换为 JSON 字符串
type JSONValue =
| null
| boolean
| number
| string
| JSONValue[]
| { [key: string]: JSONValue }
function jsonStringify(value: JSONValue): string {
if (value === null) return 'null'
if (typeof value === 'number' || typeof value === 'boolean')
return String(value)
if (typeof value === 'string') return `"${value}"`
if (Array.isArray(value)) {
const res = value.map((v) => jsonStringify(v))
return `[${res.join(',')}]`
}
if (typeof value === 'object') {
const res = Object.entries(value).map(
([key, val]) => `"${key}":${jsonStringify(val)}`
)
return `{${res.join(',')}}`
}
return ''
}