import { describe, test, expect, Result } from './tests.uts' class User{ name:string = ""; age:number = 12; } export function testJSON() : Result { return describe("JSON", () => { test('parse', () => { const json = `{"result":true, "count":42}`; const obj = JSON.parse(json)!; expect(obj["count"]).toEqual(42); expect(obj["result"] as boolean).toEqual(true); const json1 = `{ "name": "John", "age": 30, "city": "New York" }`; const obj1 = JSON.parse(json1); expect(obj1).toEqual({ name: 'John', age: 30, city: 'New York', }); const json2 = '{"string":"Hello","number":42,"boolean":true,"nullValue":null,"array":[1,2,3],"object":{"nestedKey":"nestedValue"}}'; const obj2 = JSON.parse(json2)!; expect(obj2).toEqual({ string: 'Hello', number: 42, boolean: true, nullValue: null, array: [1, 2, 3], object: { nestedKey: 'nestedValue', }, }); expect(obj2['object']).toEqual({ nestedKey: 'nestedValue', }) // 目前仅android 支持,暂不放开 // let obj3 = JSON.parse(json1); // console.log(obj3) // const json3 = '["apple","banana","cherry"]'; // const obj3 = JSON.parse(json3)!; // TODO JSON.parse 后数组的类型 无法强转 // expect(obj3).toEqual(['apple', 'banana', 'cherry']); // const json4 = '[1, "two", true, null, {"key": "value"}, ["nested"]]'; // const obj4 = JSON.parse(json4)!; // expect(obj4).toEqual([1, 'two', true, null, { key: 'value' }, ['nested']]); // TODO 暂不支持多个参数 // const json5 = '{"p": 5}'; // const obj5 = JSON.parse(json5, function (k : string, v : number) : number { // if (k === '') return v; // return v * 2; // })!; // expect(obj5).toEqual({ // p: 10, // }); expect(JSON.parse('{}')!).toEqual({}); // TODO 不支持boolean、string,js端需抹平 // expect(JSON.parse('true')!).toEqual(true); // expect(JSON.parse('"foo"')!).toEqual("foo"); // expect(JSON.parse('null')!).toEqual(null); }) test('stringify', () => { const obj = { name: 'John', age: 30 }; const json = JSON.stringify(obj); expect(json).toEqual('{"name":"John","age":30}'); const obj1 = { name: 'John', age: 30, address: { city: 'New York', country: 'USA' } }; const json1 = JSON.stringify(obj1); expect(json1).toEqual('{"name":"John","age":30,"address":{"city":"New York","country":"USA"}}'); const obj2 = ['apple', 'banana', 'cherry']; const json2 = JSON.stringify(obj2); expect(json2).toEqual('["apple","banana","cherry"]'); // TODO 暂不支持多个参数 // const obj3 = { name: 'John', age: '30' }; // const replacer = (key : string, value : string) : string => (key === 'name' ? value.toUpperCase() : value); // const json3 = JSON.stringify(obj3, replacer); // expect(json3).toEqual('{"name":"JOHN","age":"30"}'); // const obj4 = { name: 'John', age: 30 }; // const json4 = JSON.stringify(obj4, null, 4); // expect(json4).toEqual(`{ // "name": "John", // "age": 30 // }`); expect(JSON.stringify({ x: 5, y: 6 })).toEqual(`{"x":5,"y":6}`); expect(JSON.stringify([3, 'false', false])).toEqual(`[3,"false",false]`); expect(JSON.stringify({})).toEqual('{}'); expect(JSON.stringify(true)).toEqual('true'); expect(JSON.stringify('foo')).toEqual('foo'); }) }) }