fix: 将json清洗操作封装为函数

refactor: 将json编解码操作放入/utils/parse
This commit is contained in:
roitium 2024-07-24 10:18:24 +08:00
parent c985e5b08f
commit 208b2db60b
4 changed files with 36 additions and 20 deletions

View File

@ -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";

View File

@ -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;
}

View File

@ -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
View 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;
}
}