File tree 3 files changed +69
-2
lines changed
solution/2600-2699/2633.Convert Object to JSON String
3 files changed +69
-2
lines changed Original file line number Diff line number Diff line change @@ -68,7 +68,29 @@ JSON 的基本类型是字符串、数字型、布尔值和 null。
68
68
<!-- 这里可写当前语言的特殊实现逻辑 -->
69
69
70
70
``` ts
71
-
71
+ function jsonStringify(object : any ): string {
72
+ if (object === null ) {
73
+ return ' null' ;
74
+ }
75
+ if (typeof object === ' string' ) {
76
+ return ` "${object }" ` ;
77
+ }
78
+ if (typeof object === ' number' || typeof object === ' boolean' ) {
79
+ return object .toString ();
80
+ }
81
+ if (Array .isArray (object )) {
82
+ return ` [${object .map (jsonStringify ).join (' ,' )}] ` ;
83
+ }
84
+ if (typeof object === ' object' ) {
85
+ return ` {${Object .entries (object )
86
+ .map (
87
+ ([key , value ]) =>
88
+ ` ${jsonStringify (key )}:${jsonStringify (value )} ` ,
89
+ )
90
+ .join (' ,' )}} ` ;
91
+ }
92
+ return ' ' ;
93
+ }
72
94
```
73
95
74
96
### ** ...**
Original file line number Diff line number Diff line change @@ -60,7 +60,29 @@ Primitive types are valid inputs.</pre>
60
60
### ** TypeScript**
61
61
62
62
``` ts
63
-
63
+ function jsonStringify(object : any ): string {
64
+ if (object === null ) {
65
+ return ' null' ;
66
+ }
67
+ if (typeof object === ' string' ) {
68
+ return ` "${object }" ` ;
69
+ }
70
+ if (typeof object === ' number' || typeof object === ' boolean' ) {
71
+ return object .toString ();
72
+ }
73
+ if (Array .isArray (object )) {
74
+ return ` [${object .map (jsonStringify ).join (' ,' )}] ` ;
75
+ }
76
+ if (typeof object === ' object' ) {
77
+ return ` {${Object .entries (object )
78
+ .map (
79
+ ([key , value ]) =>
80
+ ` ${jsonStringify (key )}:${jsonStringify (value )} ` ,
81
+ )
82
+ .join (' ,' )}} ` ;
83
+ }
84
+ return ' ' ;
85
+ }
64
86
```
65
87
66
88
### ** ...**
Original file line number Diff line number Diff line change
1
+ function jsonStringify ( object : any ) : string {
2
+ if ( object === null ) {
3
+ return 'null' ;
4
+ }
5
+ if ( typeof object === 'string' ) {
6
+ return `"${ object } "` ;
7
+ }
8
+ if ( typeof object === 'number' || typeof object === 'boolean' ) {
9
+ return object . toString ( ) ;
10
+ }
11
+ if ( Array . isArray ( object ) ) {
12
+ return `[${ object . map ( jsonStringify ) . join ( ',' ) } ]` ;
13
+ }
14
+ if ( typeof object === 'object' ) {
15
+ return `{${ Object . entries ( object )
16
+ . map (
17
+ ( [ key , value ] ) =>
18
+ `${ jsonStringify ( key ) } :${ jsonStringify ( value ) } ` ,
19
+ )
20
+ . join ( ',' ) } }`;
21
+ }
22
+ return '' ;
23
+ }
You can’t perform that action at this time.
0 commit comments