mirror of
https://github.com/idootop/mi-gpt.git
synced 2025-04-13 21:11:52 +00:00
fix: 将json清洗操作封装为函数
refactor: 将json编解码操作放入/utils/parse
This commit is contained in:
parent
c985e5b08f
commit
208b2db60b
|
@ -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";
|
||||
|
|
|
@ -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<T = any>(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<T = any>(e: any, defaultValue: T): T {
|
||||
return isEmpty(e) ? defaultValue : e;
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
|
||||
|
|
32
src/utils/parse.ts
Normal file
32
src/utils/parse.ts
Normal file
|
@ -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;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user