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 text. 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.<br> 21When 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> 22When used as a parameter of [JSON.stringify](#jsonstringify-1), the function is used to transfer and handle each property during serialization. 23 24**Atomic service API**: This API can be used in atomic services since API version 12. 25 26**System capability**: SystemCapability.Utils.Lang 27 28**Parameters** 29 30| Name| Type | Mandatory| Description | 31| ------ | ------ | ---- | --------------- | 32| this | Object | Yes| Object to which the key-value pair to parse belongs.| 33| key | string | Yes| Key to parse.| 34| value | Object | Yes| Value of the key.| 35 36**Returns** 37 38| Type| Description| 39| -------- | -------- | 40| Object \| undefined \| null | Object obtained after parsing, undefined, or null.| 41 42## BigIntMode 43 44Enumerates the modes for processing BigInt. 45 46**Atomic service API**: This API can be used in atomic services since API version 12. 47 48**System capability**: SystemCapability.Utils.Lang 49 50| Name| Value| Description | 51| ------ | ------ | --------------- | 52| DEFAULT | 0 |BigInt is not supported.| 53| PARSE_AS_BIGINT | 1 |Parses an integer that is less than -(2^53-1) or greater than (2^53-1) as BigInt.| 54| ALWAYS_PARSE_AS_BIGINT | 2 |Parses all integers as BigInt.| 55 56## ParseOptions 57 58Describes the parsing options, which can define the mode for processing BigInt. 59 60**Atomic service API**: This API can be used in atomic services since API version 12. 61 62**System capability**: SystemCapability.Utils.Lang 63 64| Name| Type| Mandatory|Description | 65| ------ | ------ | ---- | --------------- | 66| bigIntMode | [BigIntMode](#bigintmode) | Yes|Mode for processing BigInt.| 67 68## JSON.parse 69 70parse(text: string, reviver?: Transformer, options?: ParseOptions): Object | null 71 72Parses a JSON string into an ArkTS object or null. 73 74**Atomic service API**: This API can be used in atomic services since API version 12. 75 76**System capability**: SystemCapability.Utils.Lang 77 78**Parameters** 79 80| Name| Type | Mandatory| Description | 81| ------ | ------ | ---- | --------------- | 82| text | string | Yes| Valid JSON string.| 83| reviver | [Transformer](#transformer) | No| Conversion function. This parameter can be used to modify the value generated after parsing. The default value is undefined.| 84| options | [ParseOptions](#parseoptions) | No| Parsing options. This parameter is used to control the type of the parsing result. The default value is undefined.| 85 86**Returns** 87 88| Type| Description| 89| -------- | -------- | 90| Object \| null | ArkTS object or null (if null is passed in).| 91 92**Error codes** 93 94For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 95 96| ID| Error Message| 97| -------- | -------- | 98| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 99 100**Example** 101<!--code_no_check--> 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 { JSON } from '@kit.ArkTS'; 115import { reviverFunc } from './test'; 116 117let jsonText = '{"name": "John", "age": 30, "city": "ChongQing"}'; 118let obj = JSON.parse(jsonText); 119console.info((obj as object)?.["name"]); 120// Output: John 121const jsonTextStr = '{"name": "John", "age": 30}'; 122let objRst = JSON.parse(jsonTextStr, reviverFunc); 123console.info((objRst as object)?.["age"]); 124// Output: 31 125let options: JSON.ParseOptions = { 126 bigIntMode: JSON.BigIntMode.PARSE_AS_BIGINT, 127} 128let numberText = '{"largeNumber":112233445566778899}'; 129let numberObj = JSON.parse(numberText,(key: string, value: Object | undefined | null): Object | undefined | null => { 130 if(key === "largeNumber") return value; 131 return value; 132},options) as Object; 133 134console.info((numberObj as object)?.["largeNumber"]); 135// Output: 112233445566778899 136``` 137 138```ts 139import { JSON } from '@kit.ArkTS'; 140 141/* 142 * Deserialize JSON strings with nested quotation marks. 143 * */ 144 145interface Info { 146 name: string; 147 age: number; 148} 149 150interface TestObj { 151 info: Info; 152} 153 154interface TestStr { 155 info: string; 156} 157 158// The JSON string contains nested quotation marks. This breaks the JSON structure, making it impossible to deserialize properly. 159// let jsonStr = `{"info": "{"name": "zhangsan", "age": 18}"}`; 160 161// The following provides two methods to solve this problem: 162// Method 1: Avoid nested operations. Convert "{"name": "zhangsan", "age": 18}" in the original JSON string to {"name": "zhangsan", "age": 18}. 163let jsonStr = `{"info": {"name": "zhangsan", "age": 18}}`; 164let obj1 = JSON.parse(jsonStr) as TestObj; 165console.info(JSON.stringify(obj1)); //{"info":{"name":"zhangsan","age":18}} 166// Obtain the name property in the JSON string. 167console.info(obj1.info.name); // zhangsan 168 169// Method 2: Escape the nested quotation marks in the JSON string to restore the proper JSON structure. 170jsonStr = `{"info": "{\\"name\\": \\"zhangsan\\", \\"age\\": 18}"}`; 171let obj2 = JSON.parse(jsonStr) as TestStr;; 172console.info(JSON.stringify(obj2)); // {"info":"{\"name\": \"zhangsan\", \"age\": 18}"} 173// Obtain the name property in the JSON string. 174let obj3 = JSON.parse(obj2.info) as Info; 175console.info(obj3.name); // zhangsan 176``` 177 178## JSON.stringify 179 180stringify(value: Object, replacer?: (number | string)[] | null, space?: string | number): string 181 182Converts 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. 183 184**Atomic service API**: This API can be used in atomic services since API version 12. 185 186**System capability**: SystemCapability.Utils.Lang 187 188**Parameters** 189 190| Name| Type| Mandatory| Description| 191| -------- | -------- | -------- | -------- | 192| value | Object | Yes| ArkTS object or array. In the case of a container, linear containers are supported, but non-linear containers are not.| 193| 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.| 194| space | string \| number | No| White spaces or strings inserted into the output JSON string for readability purposes. If the parameter is a number, it represents the number of indentation spaces; if it is a string, it represents the indentation characters. If no parameter is provided, there will be no indentation. The default value is an empty string.| 195 196**Returns** 197 198| Type| Description| 199| -------- | -------- | 200| string | JSON string after conversion.| 201 202**Error codes** 203 204For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 205 206| ID| Error Message| 207| -------- | -------- | 208| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 209 210**Example** 211<!--code_no_check--> 212```ts 213// /entry/src/main/ets/pages/test.ts 214export let exportObj = {1: "John", 2: 30, 3: "New York"}; 215``` 216 217<!--code_no_check--> 218```ts 219import { JSON } from '@kit.ArkTS'; 220import { exportObj } from './test'; 221 222let arr = [1, 2]; 223let rstArrStr = JSON.stringify(exportObj, arr); 224console.info(rstArrStr); 225// Output: "{"1":"John,""2":30}" 226interface Person { 227 name: string; 228 age: number; 229 city: string; 230} 231let inputObj = {"name": "John", "age": 30, "city": "ChongQing"} as Person; 232let rstStr = JSON.stringify(inputObj, ["name"]); 233console.info(rstStr); 234// Output: "{"name":"John"}" 235let rstStrSpace = JSON.stringify(inputObj, ["name"], ' '); 236console.info(rstStrSpace); 237// Output: 238/* 239"{ 240 "name": "John" 241}" 242*/ 243let rstStrStar = JSON.stringify(inputObj, ["name"], '&&'); 244console.info(rstStrStar); 245// Output: 246/* 247"{ 248&&"name": "John" 249}" 250*/ 251``` 252 253 254## JSON.stringify 255 256stringify(value: Object, replacer?: Transformer, space?: string | number): string 257 258Converts 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. 259 260**Atomic service API**: This API can be used in atomic services since API version 12. 261 262**System capability**: SystemCapability.Utils.Lang 263 264**Parameters** 265 266| Name| Type| Mandatory| Description| 267| -------- | -------- | -------- | -------- | 268| value | Object | Yes| ArkTS object or array. In the case of a container, linear containers are supported, but non-linear containers are not.| 269| replacer | [Transformer](#transformer) | No| During serialization, each key of the serialized value is converted and processed by this function. The default value is undefined.| 270| 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.| 271 272**Returns** 273 274| Type| Description| 275| -------- | -------- | 276| string | JSON string after conversion.| 277 278**Error codes** 279 280For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 281 282| ID| Error Message| 283| -------- | -------- | 284| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 285 286**Example** 287```ts 288// /entry/src/main/ets/pages/test.ts 289export function replacer(key: string, value: Object): Object { 290 if (typeof value === "string") { 291 return value.toUpperCase(); 292 } 293 return value; 294} 295``` 296 297<!--code_no_check--> 298```ts 299import { JSON } from '@kit.ArkTS'; 300import { replacer } from './test'; 301 302interface Person { 303 name: string; 304 age: number; 305 city: string; 306} 307let inputObj = {"name": "John", "age": 30, "city": "ChongQing"} as Person; 308let rstStr= JSON.stringify(inputObj, replacer); 309console.info(rstStr); 310// Output: "{"name":"JOHN,""age":30,"city":"CHONGQING"}" 311let rstStrSpace= JSON.stringify(inputObj, replacer, ' '); 312console.info(rstStrSpace); 313// Output: 314/* 315"{ 316 "name": "JOHN", 317 "age": 30, 318 "city": "CHONGQING" 319}" 320*/ 321let rstStrSymbol= JSON.stringify(inputObj, replacer, '@@@'); 322console.info(rstStrSymbol); 323// Output: 324/* 325"{ 326@@@"name": "JOHN", 327@@@"age": 30, 328@@@"city": "CHONGQING" 329}" 330*/ 331``` 332 333```ts 334import { JSON } from '@kit.ArkTS'; 335 336/* 337 * Serialize BigInt objects. 338 * */ 339let bigIntObject = BigInt(112233445566778899) 340 341/* 342 * Scenario 1: Serialize a BigInt object without a custom conversion function. 343 * */ 344console.info(JSON.stringify(bigIntObject)); // 112233445566778896 345 346/* 347 * Scenario 2: Use a custom conversion function to serialize a BigInt object. 348 * 2.1 Directly returning a BigInt object in the custom function will cause a JSCrash. 349 * 2.2 Use a custom conversion function to preprocess the BigInt object as a string for serialization. 350 * */ 351 352// 2.1 Incorrect serialization approach: Directly return a BigInt object in the custom function. 353// JSON.stringify(bigIntObject, (key: string, value: Object): Object =>{ return value; }); 354 355// 2.2 Correct serialization approach: Preprocess the BigInt object as a string in the custom function. 356let result: string = JSON.stringify(bigIntObject, (key: string, value: Object): Object => { 357 if (typeof value === 'bigint') { 358 return value.toString(); 359 } 360 return value; 361}); 362console.info("result:", result); // result: "112233445566778896" 363``` 364 365```ts 366import { JSON } from '@kit.ArkTS'; 367 368/* 369 * Serialize floating-point numbers. 370 * */ 371let floatNumber1 = 10.12345; 372let floatNumber2 = 10.00; 373 374// Serializing a floating-point number with a non-zero fractional part works as expected. 375let result1 = JSON.stringify(floatNumber1); 376console.info(result1); // 10.12345 377 378// Serializing a floating-point number with a zero fractional part results in the loss of fractional precision for a more concise representation. 379let result11 = JSON.stringify(floatNumber2); 380console.info(result11); // 10 381 382// The following is a method to prevent the loss of floating-point precision: 383let result2 = JSON.stringify(floatNumber2, (key: string, value: Object): Object => { 384 if (typeof value === 'number') { 385 // Customize the fixed precision as needed for your specific use case. 386 return value.toFixed(2); 387 } 388 return value; 389}); 390console.info(result2); // "10.00" 391``` 392 393## JSON.has 394 395has(obj: object, property: string): boolean 396 397Checks 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). 398 399**Atomic service API**: This API can be used in atomic services since API version 12. 400 401**System capability**: SystemCapability.Utils.Lang 402 403**Parameters** 404 405| Name| Type| Mandatory| Description| 406| -------- | -------- | -------- | -------- | 407| obj | object | Yes| ArkTS object.| 408| property | string | Yes| Key to check.| 409 410**Returns** 411 412| Type| Description| 413| -------- | -------- | 414| boolean | Check result. The value **true** is returned if the ArkTS object contains the key; otherwise, **false** is returned.| 415 416**Error codes** 417 418For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 419 420| ID| Error Message| 421| -------- | -------- | 422| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 423 424**Example** 425 426```ts 427import { JSON } from '@kit.ArkTS'; 428 429const jsonText = '{"name": "John", "age": 30, "city": "ChongQing"}'; 430let inputObj = JSON.parse(jsonText); 431let result = JSON.has(inputObj, "name"); 432console.info("result = " + result); 433// Output: result = true 434``` 435 436 437## JSON.remove 438 439remove(obj: object, property: string): void 440 441Removes 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). 442 443**Atomic service API**: This API can be used in atomic services since API version 12. 444 445**System capability**: SystemCapability.Utils.Lang 446 447**Parameters** 448 449| Name| Type| Mandatory| Description| 450| -------- | -------- | -------- | -------- | 451| obj | object | Yes| ArkTS object.| 452| property | string | Yes| Key to remove.| 453 454**Error codes** 455 456For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 457 458| ID| Error Message| 459| -------- | -------- | 460| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 461 462**Example** 463 464```ts 465import { JSON } from '@kit.ArkTS'; 466 467const jsonText = '{"name": "John", "age": 30, "city": "ChongQing"}'; 468let inputObj = JSON.parse(jsonText); 469JSON.remove(inputObj, "name"); 470let result = JSON.has(inputObj, "name"); 471console.info("result = " + result); 472// Output: result = false 473``` 474