1/* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import {json} from "@ohos.util.json"; 17 18class SubObj { 19 s: string = "qwerty" 20} 21class ObjToDump { 22 a: bigint = new BigInt(1) 23 b: string = "abcbcb" 24 c: Number = 21222.22219 25 d: undefined = undefined 26 e: SubObj = new SubObj() 27} 28 29function main(): void { 30 testStringigyEmptyStr() 31 testStringifyObj() 32 testStringifyObjWithArrayReplacer() 33 testStringifyObjWithFuncReplacer() 34 testStringifyObjNullReplacer() 35 testStringifyObjUndefReplacer() 36 testStringifyNull() 37 testStringifyUndefined() 38} 39 40function testStringigyEmptyStr() { 41 assertEQ(json.stringify(""), "\"\"") 42} 43 44function testStringifyObj() { 45 assertEQ(json.stringify(new ObjToDump()), "{\"a\":1,\"b\":\"abcbcb\",\"c\":21222.22219,\"e\":{\"s\":\"qwerty\"}}") 46} 47 48function testStringifyObjWithArrayReplacer() { 49 assertEQ(json.stringify(new ObjToDump(), ["a", "b"]), "{\"a\":1,\"b\":\"abcbcb\"}" ) 50} 51 52function testStringifyObjWithFuncReplacer() { 53 let f = (k: string, value: NullishType): NullishType => { 54 if (k === "a") { 55 return 77777 56 } else if (k === "not existing") { 57 return "blablabla" 58 } 59 return value 60 } 61 assertEQ(json.stringify(new ObjToDump(), f, " "), "{\n" + " \"a\": 77777,\n" + " \"b\": \"abcbcb\",\n" + 62 " \"c\": 21222.22219,\n" + " \"e\": {\n" + " \"s\": \"qwerty\"\n" + " }\n" +"}") 63} 64 65function testStringifyObjNullReplacer() { 66 assertEQ(json.stringify(new ObjToDump(), null, 0), "{\"a\":1,\"b\":\"abcbcb\",\"c\":21222.22219,\"e\":{\"s\":\"qwerty\"}}") 67} 68 69function testStringifyObjUndefReplacer() { 70 assertEQ(json.stringify(new ObjToDump(), undefined, 0), "{\"a\":1,\"b\":\"abcbcb\",\"c\":21222.22219,\"e\":{\"s\":\"qwerty\"}}") 71} 72 73function testStringifyNull() { 74 assertEQ(json.stringify(null, undefined, 0), "null") 75} 76 77function testStringifyUndefined() { 78 assertEQ(json.stringify(undefined, undefined, 0), "undefined") 79} 80