# 2633. Convert Object to JSON String ###### tags: `leetcode 30 days js challenge` `Medium` [2633. Convert Object to JSON String](https://leetcode.com/problems/convert-object-to-json-string/) ### 題目描述 Given an object, return a valid JSON string of that object. You may assume the object only inludes strings, integers, arrays, objects, booleans, and null. The returned string should not include extra spaces. The order of keys should be the same as the order returned by `Object.keys()`. Please solve it without using the built-in `JSON.stringify` method. ### 範例 **Example 1:** ``` Input: object = {"y":1,"x":2} Output: {"y":1,"x":2} Explanation: Return the JSON representation. Note that the order of keys should be the same as the order returned by Object.keys(). ``` **Example 2:** ``` Input: object = {"a":"str","b":-12,"c":true,"d":null} Output: {"a":"str","b":-12,"c":true,"d":null} Explanation: The primitives of JSON are strings, numbers, booleans, and null. ``` **Example 3:** ``` Input: object = {"key":{"a":1,"b":[{},null,"Hello"]}} Output: {"key":{"a":1,"b":[{},null,"Hello"]}} Explanation: Objects and arrays can include other objects and arrays. ``` **Example 4:** ``` Input: object = true Output: true Explanation: Primitive types are valid inputs. ``` **Constraints**: - `object includes strings, integers, booleans, arrays, objects, and null` - `1 <= JSON.stringify(object).length <= 105` - `maxNestingLevel <= 1000` - `all strings will only contain alphanumeric characters` ### 解答 #### TypeScript ```typescript= function jsonStringify(object: any): string { // string 需要用 "" 包 if (typeof object === 'string') { return `"${object}"`; } if (Array.isArray(object)) { // array 需要用 `[]` 包,並使用 `join(',')` 分隔 return `[${object.map((item) => jsonStringify(item)).join(',')}]`; } else if (typeof object === 'object' && object !== null) { // object 可以使用一個陣列來存放所有的 `"key":value` 字串,最後用 `join(',')` 來分隔 const oKeys = Object.keys(object); const props: string[] = oKeys.map((key) => `"${key}":${jsonStringify(object[key])}`); return `{${props.join(',')}}`; } // number, boolean, null return String(object); } ``` 使用 Switch Case: ```typescript= function jsonStringify(object: any): string { switch (typeof object) { case 'object': if (Array.isArray(object)) { return `[${object.map((item) => jsonStringify(item)).join(',')}]`; } else if (object) { const oKeys = Object.keys(object); const keyValuePairs: string[] = oKeys.map( (key) => `"${key}":${jsonStringify(object[key])}` ); return `{${keyValuePairs.join(',')}}`; } else { return 'null'; } case 'boolean': case 'number': return `${object}`; case 'string': return `"${object}"`; default: return ''; } } ``` > [name=Sheep][time=Mon, May 22, 2023] ### Reference [回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)