• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.util.json (JSON解析与生成)
2
3本模块提供了将JSON文本转换为JSON对应对象或值,以及将对象转换为JSON字符串等功能。
4
5>**说明:**
6>
7>本模块首批接口从API version 12开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8
9
10## 导入模块
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
20用于转换结果函数的类型。<br>
21作为[JSON.parse](#jsonparse)函数的参数时,对象的每个成员将会调用此函数,解析过程中允许对数据进行自定义处理或转换。<br>
22作为[JSON.stringify](#jsonstringify-1)函数的参数时,在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理。
23
24**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
25
26**系统能力:** SystemCapability.Utils.Lang
27
28**参数:**
29
30| 参数名 | 类型   | 必填 | 说明            |
31| ------ | ------ | ---- | --------------- |
32| this   | Object | 是 | 在解析的键值对所属的对象。|
33| key  | string | 是 | 属性名。|
34| value  | Object | 是 | 在解析的键值对的值。|
35
36**返回值:**
37
38| 类型 | 说明 |
39| -------- | -------- |
40| Object \| undefined \| null | 返回修改后的对象或undefined或null。|
41
42## BigIntMode
43
44定义处理BigInt的模式。
45
46**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
47
48**系统能力:** SystemCapability.Utils.Lang
49
50| 名称 | 值| 说明            |
51| ------ | ------ | --------------- |
52| DEFAULT   | 0 |不支持BigInt。|
53| PARSE_AS_BIGINT   | 1 |当整数小于-(2^53-1)或大于(2^53-1)时,解析为BigInt。|
54| ALWAYS_PARSE_AS_BIGINT   | 2 |所有整数都解析为BigInt。|
55
56## ParseOptions
57
58解析的选项,可定义处理BigInt的模式。
59
60**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
61
62**系统能力:** SystemCapability.Utils.Lang
63
64| 名称 | 类型| 必填 |说明            |
65| ------ | ------ | ---- | --------------- |
66| bigIntMode   | [BigIntMode](#bigintmode) | 是 |定义处理BigInt的模式。|
67
68## JSON.parse
69
70parse(text: string, reviver?: Transformer, options?: ParseOptions): Object | null
71
72用于解析JSON字符串生成对应ArkTS对象或null。
73
74**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
75
76**系统能力:** SystemCapability.Utils.Lang
77
78**参数:**
79
80| 参数名 | 类型   | 必填 | 说明            |
81| ------ | ------ | ---- | --------------- |
82| text   | string | 是 | 有效的JSON字符串。|
83| reviver  | [Transformer](#transformer) | 否 | 转换函数,传入该参数,可以用来修改解析生成的原始值。默认值是undefined。|
84| options   | [ParseOptions](#parseoptions) | 否 | 解析的配置,传入该参数,可以用来控制解析生成的类型。默认值是undefined。|
85
86**返回值:**
87
88| 类型 | 说明 |
89| -------- | -------- |
90| Object \| null | 返回ArkTS对象或null。当入参是null时,返回null。|
91
92**错误码:**
93
94以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
95
96| 错误码ID | 错误信息 |
97| -------- | -------- |
98| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
99
100**示例:**
101
102```ts
103// /entry/src/main/ets/pages/test.ts
104export function reviverFunc(key, value) {
105  if (key === "age") {
106    return value + 1;
107  }
108  return value;
109}
110```
111
112<!--code_no_check-->
113```ts
114import { reviverFunc } from './test';
115
116let jsonText = '{"name": "John", "age": 30, "city": "ChongQing"}';
117let obj = JSON.parse(jsonText);
118console.info((obj as object)?.["name"]);
119// 打印结果:John
120const jsonTextStr = '{"name": "John", "age": 30}';
121let objRst = JSON.parse(jsonTextStr, reviverFunc);
122console.info((objRst as object)?.["age"]);
123// 打印结果:31
124let options: JSON.ParseOptions = {
125  bigIntMode: JSON.BigIntMode.PARSE_AS_BIGINT,
126}
127let numberText = '{"largeNumber":112233445566778899}';
128let numberObj = JSON.parse(numberText,(key: string, value: Object | undefined | null): Object | undefined | null => {
129  if(key === "largeNumber") return value;
130  return value;
131},options) as Object;
132
133console.info((numberObj as object)?.["largeNumber"]);
134// 打印结果: 112233445566778899
135```
136
137
138## JSON.stringify
139
140stringify(value: Object, replacer?: (number | string)[] | null, space?: string | number): string
141
142该方法将一个ArkTS对象或数组转换为JSON字符串,对于容器支持线性容器转换,非线性的容器不支持。
143
144**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
145
146**系统能力:** SystemCapability.Utils.Lang
147
148**参数:**
149
150| 参数名 | 类型 | 必填 | 说明 |
151| -------- | -------- | -------- | -------- |
152| value | Object | 是 | ArkTS对象或数组,对于容器支持线性容器转换,非线性的容器不支持。|
153| replacer | number[] \| string[] \| null | 否 | 当参数是数组时,只有包含在这个数组中的属性名才会被序列化到最终的JSON字符串中;当参数为null或者未提供时,则对象所有的属性都会被序列化。默认值是undefined。|
154| space | string \| number | 否 | 指定缩进用的空格或字符串或空字符串,用于美化输出。当参数是数字时表示有多少个空格;当参数是字符串时,该字符串被当作空格;当参数没有提供时,将没有空格。默认值是空字符串。|
155
156**返回值:**
157
158| 类型 | 说明 |
159| -------- | -------- |
160| string | 转换后的JSON字符串。|
161
162**错误码:**
163
164以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
165
166| 错误码ID | 错误信息 |
167| -------- | -------- |
168| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
169
170**示例:**
171```ts
172// /entry/src/main/ets/pages/test.ts
173export let exportObj = {1: "John", 2: 30, 3: "New York"};
174```
175
176<!--code_no_check-->
177```ts
178import { exportObj } from './test';
179
180let arr = [1, 2];
181let rstArrStr = JSON.stringify(exportObj, arr);
182console.info(rstArrStr);
183// 打印结果:"{"1":"John","2":30}"
184interface Person {
185  name: string;
186  age: number;
187  city: string;
188}
189let inputObj = {"name": "John", "age": 30, "city": "ChongQing"} as Person;
190let rstStr = JSON.stringify(inputObj, ["name"]);
191console.info(rstStr);
192// 打印结果:"{"name":"John"}"
193let rstStrSpace = JSON.stringify(inputObj, ["name"], '  ');
194console.info(rstStrSpace);
195// 打印结果:
196/*
197"{
198  "name": "John"
199}"
200*/
201let rstStrStar = JSON.stringify(inputObj, ["name"], '&&');
202console.info(rstStrStar);
203// 打印结果:
204/*
205"{
206&&"name": "John"
207}"
208*/
209```
210
211
212## JSON.stringify
213
214stringify(value: Object, replacer?: Transformer, space?: string | number): string
215
216该方法将一个ArkTS对象或数组转换为JSON字符串,对于容器支持线性容器转换,非线性的容器不支持。
217
218**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
219
220**系统能力:** SystemCapability.Utils.Lang
221
222**参数:**
223
224| 参数名 | 类型 | 必填 | 说明 |
225| -------- | -------- | -------- | -------- |
226| value | Object | 是 | ArkTS对象或数组,对于容器支持线性容器转换,非线性的容器不支持。|
227| replacer | [Transformer](#transformer) | 否 | 在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理。默认值是undefined。|
228| space | string \| number | 否 | 指定缩进用的空格或字符串或空字符串,用于美化输出。当参数是数字时表示有多少个空格;当参数是字符串时,该字符串被当作空格;当参数没有提供时,将没有空格。默认值是空字符串。|
229
230**返回值:**
231
232| 类型 | 说明 |
233| -------- | -------- |
234| string | 转换后的JSON字符串。|
235
236**错误码:**
237
238以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
239
240| 错误码ID | 错误信息 |
241| -------- | -------- |
242| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
243
244**示例:**
245```ts
246// /entry/src/main/ets/pages/test.ts
247export function replacer(key: string, value: Object): Object {
248  if (typeof value === "string") {
249    return value.toUpperCase();
250  }
251  return value;
252}
253```
254
255<!--code_no_check-->
256```ts
257import { replacer } from './test';
258
259interface Person {
260  name: string;
261  age: number;
262  city: string;
263}
264let inputObj = {"name": "John", "age": 30, "city": "ChongQing"} as Person;
265let rstStr= JSON.stringify(inputObj, replacer);
266console.info(rstStr);
267// 打印结果:"{"name":"JOHN","age":30,"city":"CHONGQING"}"
268let rstStrSpace= JSON.stringify(inputObj, replacer, '  ');
269console.info(rstStrSpace);
270// 打印结果:
271/*
272"{
273  "name": "JOHN",
274  "age": 30,
275  "city": "CHONGQING"
276}"
277*/
278let rstStrSymbol= JSON.stringify(inputObj, replacer, '@@@');
279console.info(rstStrSymbol);
280// 打印结果:
281/*
282"{
283@@@"name": "JOHN",
284@@@"age": 30,
285@@@"city": "CHONGQING"
286}"
287*/
288```
289
290
291## JSON.has
292
293has(obj: object, property: string): boolean
294
295检查ArkTS对象是否包含某种属性,可用于[JSON.parse](#jsonparse)解析JSON字符串之后的相关操作。has接口仅支持最外层为字典形式(即大括号而非中括号包围)的合法json串。
296
297**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
298
299**系统能力:** SystemCapability.Utils.Lang
300
301**参数:**
302
303| 参数名 | 类型 | 必填 | 说明 |
304| -------- | -------- | -------- | -------- |
305| obj | object | 是 | ArkTS对象。|
306| property | string | 是 | 属性名。|
307
308**返回值:**
309
310| 类型 | 说明 |
311| -------- | -------- |
312| boolean | 返回ArkTS对象是否包含某种属性结果,true表示包含,false表示不包含。|
313
314**错误码:**
315
316以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
317
318| 错误码ID | 错误信息 |
319| -------- | -------- |
320| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
321
322**示例:**
323
324```ts
325const jsonText = '{"name": "John", "age": 30, "city": "ChongQing"}';
326let inputObj = JSON.parse(jsonText);
327let rstflag = JSON.has(inputObj, "name");
328console.info("rstflag = " + rstflag);
329// 打印结果:rstflag = true
330```
331
332
333## JSON.remove
334
335remove(obj: object, property: string): void
336
337从ArkTS对象中删除某种属性,可用于[JSON.parse](#jsonparse)解析JSON字符串之后的相关操作。remove接口仅支持最外层为字典形式(即大括号而非中括号包围)的合法json串。
338
339**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
340
341**系统能力:** SystemCapability.Utils.Lang
342
343**参数:**
344
345| 参数名 | 类型 | 必填 | 说明 |
346| -------- | -------- | -------- | -------- |
347| obj | object | 是 | ArkTS对象。|
348| property | string | 是 | 属性名。|
349
350**错误码:**
351
352以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
353
354| 错误码ID | 错误信息 |
355| -------- | -------- |
356| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
357
358**示例:**
359
360```ts
361const jsonText = '{"name": "John", "age": 30, "city": "ChongQing"}';
362let inputObj = JSON.parse(jsonText);
363JSON.remove(inputObj, "name");
364let rstflag = JSON.has(inputObj, "name");
365console.info("rstflag = " + rstflag);
366// 打印结果:rstflag = false
367```