/* eslint-disable @typescript-eslint/no-unused-expressions */ import { expect } from 'chai'; import { isJsonString, jsonString2jsonObject } from '../../src/utils/json'; import { parseSpecialKeys } from '../../src/utils/log'; describe('utils/json', () => { it('"{\\"data\\":[{\\"uid\\":\\"aaabbcc\\"}]} 解析后应该为 { uid: \'aaabbcc\' }', () => { const fullObj = jsonString2jsonObject<{data?: {uid?: string}[]}>('"{\\"data\\":[{\\"uid\\":\\"aaabbcc\\"}]}"'); const data = fullObj?.data; let obj; if (data && data.length > 0) { obj = { uid: data[0].uid || null, }; } expect(obj).to.deep.equal({ uid: 'aaabbcc' }); }); it('{"data":[{"uid":"aaabbcc"}]} 解析后应该为 { uid: \'aaabbcc\' }', () => { const fullObj = jsonString2jsonObject<{data?: {uid?: string}[]}>('{"data":[{"uid":"aaabbcc"}]}'); const data = fullObj?.data; let obj; if (data && data.length > 0) { obj = { uid: data[0].uid || null, }; } expect(obj).to.deep.equal({ uid: 'aaabbcc' }); }); it('能够将log文件里的json数据解析为csv格式(带斜杠)', () => { const fullObj = jsonString2jsonObject<{nickname?: string}>('"{\\"nickname\\":\\"凤吖头\\\\\\"^_^\\\\\\"\\"}"'); const nickname = fullObj?.nickname; let obj; if (nickname !== undefined) { obj = { nickname }; } expect(obj).to.deep.equal({ nickname: '凤吖头"^_^"' }); }); it('解析json字符串并获取指定的字段(对象格式,多个)', () => { const obj = parseSpecialKeys('a1="{\\"data\\":[{\\"uid\\":\\"aaabbcc\\"}]}" a2=afd a3="{\\"data\\":[{\\"pid\\":\\"ddffdd\\"}]}"', [ { key: 'a1', parseFunc: (value: string | null) => { const fullObj = jsonString2jsonObject<{data?: {uid?: string}[]}>(value); const data = fullObj?.data; let res: {uid: string| null} = { uid: null }; if (data && data.length > 0) { res = { uid: data[0].uid || null, }; } return res; }, }, { key: 'a3', parseFunc: (value: string | null) => { const fullObj = jsonString2jsonObject<{data?: {pid?: string}[]}>(value); const data = fullObj?.data; let res: {pid: string| null} = { pid: null }; if (data && data.length > 0) { res = { pid: data[0].pid || null, }; } return res; }, }, ]); expect(obj).to.deep.equal({ pid: 'ddffdd', uid: 'aaabbcc' }); }); it('"{\\"a\\":\\"b\\"}" 应该是json', () => { expect(isJsonString('"{\\"a\\":\\"b\\"}"')).to.be.true; }); it('{"a":"b"} 应该是json', () => { expect(isJsonString('{"a":"b"}')).to.be.true; }); it('"aabbvc" 应该不是json', () => { expect(isJsonString('"aabbvc"')).to.be.false; }); });