diff --git a/src/services/speaker/base.ts b/src/services/speaker/base.ts index 08ac031..5875faf 100644 --- a/src/services/speaker/base.ts +++ b/src/services/speaker/base.ts @@ -5,7 +5,8 @@ import { getMiIOT, getMiNA, } from "mi-service-lite"; -import { clamp, jsonEncode, sleep } from "../../utils/base"; +import { clamp, sleep } from "../../utils/base"; +import { jsonEncode } from "../../utils/parse"; import { Logger } from "../../utils/log"; import { StreamResponse } from "./stream"; import { kAreYouOK } from "../../utils/string"; diff --git a/src/utils/base.ts b/src/utils/base.ts index e98b41a..e80fd84 100644 --- a/src/utils/base.ts +++ b/src/utils/base.ts @@ -1,4 +1,5 @@ import { isEmpty } from "./is"; +import { jsonEncode } from "./parse" export function timestamp() { return new Date().getTime(); @@ -87,24 +88,6 @@ export function toSet(datas: T[], byKey?: (e: T) => any) { return Array.from(new Set(datas)); } -export function jsonEncode(obj: any, options?: { prettier?: boolean }) { - const { prettier } = options ?? {}; - try { - return prettier ? JSON.stringify(obj, undefined, 4) : JSON.stringify(obj); - } catch (error) { - return undefined; - } -} - -export function jsonDecode(json: string | null | undefined) { - if (json == undefined) return undefined; - try { - return JSON.parse(json!); - } catch (error) { - return undefined; - } -} - export function withDefault(e: any, defaultValue: T): T { return isEmpty(e) ? defaultValue : e; } diff --git a/src/utils/io.ts b/src/utils/io.ts index 24275c0..5e07e5a 100644 --- a/src/utils/io.ts +++ b/src/utils/io.ts @@ -1,7 +1,7 @@ import fs from "fs-extra"; import path from "path"; -import { jsonDecode, jsonEncode } from "./base"; +import { jsonDecode, jsonEncode } from "./parse"; export const kRoot = process.cwd(); diff --git a/src/utils/parse.ts b/src/utils/parse.ts new file mode 100644 index 0000000..6dbdc94 --- /dev/null +++ b/src/utils/parse.ts @@ -0,0 +1,32 @@ +/** + * 清理掉json字符串前后的其他字符,并解码 + */ +export function cleanJsonAndDecode(input: string | undefined | null) { + if (input == undefined) return undefined; + const pattern = /(\{[\s\S]*?"\s*:\s*[\s\S]*?})/; + const match = input.match(pattern); + + if (!match) { + return undefined; + } + + return jsonDecode(match[0]); +} + +export function jsonEncode(obj: any, options?: { prettier?: boolean }) { + const { prettier } = options ?? {}; + try { + return prettier ? JSON.stringify(obj, undefined, 4) : JSON.stringify(obj); + } catch (error) { + return undefined; + } +} + +export function jsonDecode(json: string | null | undefined) { + if (json == undefined) return undefined; + try { + return JSON.parse(json!); + } catch (error) { + return undefined; + } +}