Skip to content

2633. Convert Object to JSON String 👍

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
type JSONValue =
  | null
  | boolean
  | number
  | string
  | JSONValue[]
  | { [key: string]: JSONValue };

function jsonStringify(object: JSONValue): string {
  if (object === null) {
    return 'null';
  }
  if (typeof object === 'boolean' || typeof object === 'number') {
    return String(object);
  }
  if (typeof object === 'string') {
    return `"${object}"`;
  }
  if (Array.isArray(object)) {
    const elems = object.map((elem) => jsonStringify(elem));
    return `[${elems.join(',')}]`;
  }
  // typeof object === 'object'
  const pairs = Object.keys(object).map(
    (key) => `"${key}":${jsonStringify(object[key])}`
  );
  return `{${pairs.join(',')}}`;
}