1# @ohos.util.json (JSON Parsing and Generation)
2
3The JSON module provides a series of APIs for converting JSON text into JSON objects or values and converting objects into JSON strings.
4
5>**NOTE**
6>
7>The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8
9
10## Modules to Import
11
12```ts
13import { JSON } from '@kit.ArkTS';
14```
15
16## Transformer
17
18type Transformer = (this: Object, key: string, value: Object) => Object | undefined | null
19
20Defines the type of the conversion result function.
21
22When used as a parameter of [JSON.parse](#jsonparse), the function is called by each member of the object, allowing for custom data processing or conversion during parsing.<br>
23
24When used as a parameter of [JSON.stringify](#jsonstringify-1), the function is used to transfer and handle each property of the object being serialized during serialization.
25
26**Atomic service API**: This API can be used in atomic services since API version 12.
27
28**System capability**: SystemCapability.Utils.Lang
29
30**Parameters**
31
32| Name| Type  | Mandatory| Description           |
33| ------ | ------ | ---- | --------------- |
34| this   | Object | Yes| Object to which the key-value pair to parse belongs.|
35| key  | string | Yes| Key to parse.|
36| value  | Object | Yes| Value of the key.|
37
38**Returns**
39
40| Type| Description|
41| -------- | -------- |
42| Object \| undefined \| null | Object obtained after parsing, undefined, or null.|
43
44## BigIntMode
45
46Enumerates the modes for processing BigInt.
47
48**Atomic service API**: This API can be used in atomic services since API version 12.
49
50**System capability**: SystemCapability.Utils.Lang
51
52| Name| Value| Description           |
53| ------ | ------ | --------------- |
54| DEFAULT   | 0 |BigInt is not supported.|
55| PARSE_AS_BIGINT   | 1 |Parses an integer that is less than -(2^53-1) or greater than (2^53-1) as BigInt.|
56| ALWAYS_PARSE_AS_BIGINT   | 2 |Parses all integers as BigInt.|
57
58## ParseOptions
59
60Describes the parsing options, which can define the mode for processing BigInt.
61
62**Atomic service API**: This API can be used in atomic services since API version 12.
63
64**System capability**: SystemCapability.Utils.Lang
65
66| Name| Type| Mandatory|Description           |
67| ------ | ------ | ---- | --------------- |
68| bigIntMode   | [BigIntMode](#bigintmode) | Yes|Mode for processing BigInt.|
69
70## JSON.parse
71
72parse(text: string, reviver?: Transformer, options?: ParseOptions): Object | null
73
74Parses a JSON string into an ArkTS object or null.
75
76**Atomic service API**: This API can be used in atomic services since API version 12.
77
78**System capability**: SystemCapability.Utils.Lang
79
80**Parameters**
81
82| Name| Type  | Mandatory| Description           |
83| ------ | ------ | ---- | --------------- |
84| text   | string | Yes| Valid JSON string.|
85| reviver  | [Transformer](#transformer) | No| Conversion function. This parameter can be used to modify the value generated after parsing. The default value is undefined.|
86| options   | [ParseOptions](#parseoptions) | No| Parsing options. This parameter is used to control the type of the parsing result. The default value is undefined.|
87
88**Returns**
89
90| Type| Description|
91| -------- | -------- |
92| Object \| null | ArkTS object or null (if null is passed in).|
93
94**Error codes**
95
96For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
97
98| ID| Error Message|
99| -------- | -------- |
100| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
101
102**Example**
103
104```ts
105// /entry/src/main/ets/pages/test.ts
106export function reviverFunc(key, value) {
107  if (key === "age") {
108    return value + 1;
109  }
110  return value;
111}
112```
113
114<!--code_no_check-->
115```ts
116import { JSON } from '@kit.ArkTS';
117import { reviverFunc } from './test';
118
119let jsonText = '{"name": "John", "age": 30, "city": "ChongQing"}';
120let obj = JSON.parse(jsonText);
121console.info((obj as object)?.["name"]);
122// Output: John
123const jsonTextStr = '{"name": "John", "age": 30}';
124let objRst = JSON.parse(jsonTextStr, reviverFunc);
125console.info((objRst as object)?.["age"]);
126// Output: 31
127let options: JSON.ParseOptions = {
128  bigIntMode: JSON.BigIntMode.PARSE_AS_BIGINT,
129}
130let numberText = '{"largeNumber":112233445566778899}';
131let numberObj = JSON.parse(numberText,(key: string, value: Object | undefined | null): Object | undefined | null => {
132  if(key === "largeNumber") return value;
133  return value;
134},options) as Object;
135
136console.info((numberObj as object)?.["largeNumber"]);
137// Output: 112233445566778899
138```
139
140
141## JSON.stringify
142
143stringify(value: Object, replacer?: (number | string)[] | null, space?: string | number): string
144
145Converts an ArkTS object or array into a JSON string. In the case of a container, linear containers are supported, but non-linear containers are not.
146
147**Atomic service API**: This API can be used in atomic services since API version 12.
148
149**System capability**: SystemCapability.Utils.Lang
150
151**Parameters**
152
153| Name| Type| Mandatory| Description|
154| -------- | -------- | -------- | -------- |
155| value | Object | Yes| ArkTS object or array. In the case of a container, linear containers are supported, but non-linear containers are not.|
156| replacer | number[] \| string[] \| null | No| If an array is passed in, only the keys in the array are serialized to the final JSON string. If null is passed in, all keys of the object are serialized. The default value is undefined.|
157| space | string \| number | No| Indentation, white space, or line break characters inserted into the output JSON string for readability purposes. If a number is passed in, it indicates the number of space characters to be used as indentation. If a string is passed in, the string is inserted before the output JSON string. If null is passed in, no white space is used. The default value is an empty string.|
158
159**Returns**
160
161| Type| Description|
162| -------- | -------- |
163| string | JSON string after conversion.|
164
165**Error codes**
166
167For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
168
169| ID| Error Message|
170| -------- | -------- |
171| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
172
173**Example**
174```ts
175// /entry/src/main/ets/pages/test.ts
176export let exportObj = {1: "John", 2: 30, 3: "New York"};
177```
178
179<!--code_no_check-->
180```ts
181import { JSON } from '@kit.ArkTS';
182import { exportObj } from './test';
183
184let arr = [1, 2];
185let rstArrStr = JSON.stringify(exportObj, arr);
186console.info(rstArrStr);
187// Output: "{"1":"John,""2":30}"
188interface Person {
189  name: string;
190  age: number;
191  city: string;
192}
193let inputObj = {"name": "John", "age": 30, "city": "ChongQing"} as Person;
194let rstStr = JSON.stringify(inputObj, ["name"]);
195console.info(rstStr);
196// Output: "{"name":"John"}"
197let rstStrSpace = JSON.stringify(inputObj, ["name"], '  ');
198console.info(rstStrSpace);
199// Output:
200/*
201"{
202  "name": "John"
203}"
204*/
205let rstStrStar = JSON.stringify(inputObj, ["name"], '&&');
206console.info(rstStrStar);
207// Output:
208/*
209"{
210&&"name": "John"
211}"
212*/
213```
214
215
216## JSON.stringify
217
218stringify(value: Object, replacer?: Transformer, space?: string | number): string
219
220Converts an ArkTS object or array into a JSON string. In the case of a container, linear containers are supported, but non-linear containers are not.
221
222**Atomic service API**: This API can be used in atomic services since API version 12.
223
224**System capability**: SystemCapability.Utils.Lang
225
226**Parameters**
227
228| Name| Type| Mandatory| Description|
229| -------- | -------- | -------- | -------- |
230| value | Object | Yes| ArkTS object or array. In the case of a container, linear containers are supported, but non-linear containers are not.|
231| replacer | [Transformer](#transformer) | No| During serialization, each key of the serialized value is converted and processed by this function. The default value is undefined.|
232| space | string \| number | No| Indentation, white space, or line break characters inserted into the output JSON string for readability purposes. If a number is passed in, it indicates the number of space characters to be used as indentation. If a string is passed in, the string is inserted before the output JSON string. If null is passed in, no white space is used. The default value is an empty string.|
233
234**Returns**
235
236| Type| Description|
237| -------- | -------- |
238| string | JSON string after conversion.|
239
240**Error codes**
241
242For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
243
244| ID| Error Message|
245| -------- | -------- |
246| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
247
248**Example**
249```ts
250// /entry/src/main/ets/pages/test.ts
251export function replacer(key: string, value: Object): Object {
252  if (typeof value === "string") {
253    return value.toUpperCase();
254  }
255  return value;
256}
257```
258
259<!--code_no_check-->
260```ts
261import { JSON } from '@kit.ArkTS';
262import { replacer } from './test';
263
264interface Person {
265  name: string;
266  age: number;
267  city: string;
268}
269let inputObj = {"name": "John", "age": 30, "city": "ChongQing"} as Person;
270let rstStr= JSON.stringify(inputObj, replacer);
271console.info(rstStr);
272// Output: "{"name":"JOHN,""age":30,"city":"CHONGQING"}"
273let rstStrSpace= JSON.stringify(inputObj, replacer, '  ');
274console.info(rstStrSpace);
275// Output:
276/*
277"{
278  "name": "JOHN",
279  "age": 30,
280  "city": "CHONGQING"
281}"
282*/
283let rstStrSymbol= JSON.stringify(inputObj, replacer, '@@@');
284console.info(rstStrSymbol);
285// Output:
286/*
287"{
288@@@"name": "JOHN",
289@@@"age": 30,
290@@@"city": "CHONGQING"
291}"
292*/
293```
294
295
296## JSON.has
297
298has(obj: object, property: string): boolean
299
300Checks whether an ArkTS object contains a key. This API can be used for related operations after [JSON.parse](#jsonparse) is called to parse a JSON string. This API supports only valid JSON strings whose outermost layer is in dictionary format (in braces instead of square brackets).
301
302**Atomic service API**: This API can be used in atomic services since API version 12.
303
304**System capability**: SystemCapability.Utils.Lang
305
306**Parameters**
307
308| Name| Type| Mandatory| Description|
309| -------- | -------- | -------- | -------- |
310| obj | object | Yes| ArkTS object.|
311| property | string | Yes| Key to check.|
312
313**Returns**
314
315| Type| Description|
316| -------- | -------- |
317| boolean | **true**: The ArkTS object contains the key.<br>**false**: The ArkTS object does not contain the key.|
318
319**Error codes**
320
321For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
322
323| ID| Error Message|
324| -------- | -------- |
325| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
326
327**Example**
328
329```ts
330import { JSON } from '@kit.ArkTS';
331
332const jsonText = '{"name": "John", "age": 30, "city": "ChongQing"}';
333let inputObj = JSON.parse(jsonText);
334let result = JSON.has(inputObj, "name");
335console.info("result = " + result);
336// Output: result = true
337```
338
339
340## JSON.remove
341
342remove(obj: object, property: string): void
343
344Removes a key from an ArkTS object. This API can be used for related operations after [JSON.parse](#jsonparse) is called to parse a JSON string. This API supports only valid JSON strings whose outermost layer is in dictionary format (in braces instead of square brackets).
345
346**Atomic service API**: This API can be used in atomic services since API version 12.
347
348**System capability**: SystemCapability.Utils.Lang
349
350**Parameters**
351
352| Name| Type| Mandatory| Description|
353| -------- | -------- | -------- | -------- |
354| obj | object | Yes| ArkTS object.|
355| property | string | Yes| Key to remove.|
356
357**Error codes**
358
359For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
360
361| ID| Error Message|
362| -------- | -------- |
363| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
364
365**Example**
366
367```ts
368import { JSON } from '@kit.ArkTS';
369
370const jsonText = '{"name": "John", "age": 30, "city": "ChongQing"}';
371let inputObj = JSON.parse(jsonText);
372JSON.remove(inputObj, "name");
373let result = JSON.has(inputObj, "name");
374console.info("result = " + result);
375// Output: result = false
376```
377