Skip to main content

2633. Convert Object to JSON String

https://leetcode.com/problems/convert-object-to-json-string/

Javascript

var jsonStringify = function(object) {
// 1. Pure type
if (typeof object !== 'object') {
return typeof object === "string" ? `"${object}"` : object.toString()
}
if (object === null) {
return 'null'
}

// 2. Array
if (Array.isArray(object)) {
let result = "["
result += object.map((child) => jsonStringify(child))
result += "]"
return result
}

// 3. Object
let result = "{"
result += Object.keys(object)
.map(key => `"${key}":${jsonStringify(object[key])}`)
.join(',')
result += "}"
return result
};

Typescript

function jsonStringify(object: any): string {
// 1. Pure type
if (typeof object !== 'object') {
return typeof object === "string" ? `"${object}"` : object.toString()
}
if (object === null) {
return 'null'
}

// 2. Array
if (Array.isArray(object)) {
let result = "["
result += object.map((child) => jsonStringify(child))
result += "]"
return result
}

// 3. Object
let result = "{"
result += Object.keys(object)
.map(key => `"${key}":${jsonStringify(object[key])}`)
.join(',')
result += "}"
return result
};