From 36c1e40d64e7befe8bec2b83e4f3596db4de9261 Mon Sep 17 00:00:00 2001 From: Gabe Date: Sat, 23 Aug 2025 00:10:42 +0800 Subject: [PATCH] feat: compatible with json strings with curly braces { --- src/apis/trans.js | 22 ++++++++++++---------- src/libs/utils.js | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/src/apis/trans.js b/src/apis/trans.js index 838eda8..24be8d4 100644 --- a/src/apis/trans.js +++ b/src/apis/trans.js @@ -39,6 +39,7 @@ import { msAuth } from "../libs/auth"; import { genDeeplFree } from "./deepl"; import { genBaidu } from "./baidu"; import interpreter from "../libs/interpreter"; +import { parseJsonObj } from "../libs/utils"; const keyMap = new Map(); const urlMap = new Map(); @@ -256,8 +257,9 @@ const genOpenAI = ({ .replaceAll(INPUT_PLACE_TO, to) .replaceAll(INPUT_PLACE_TEXT, text); - customHeader = JSON.parse("{" + customHeader + "}"); - customBody = JSON.parse("{" + customBody + "}"); + // TODO: 同时支持json对象和hook函数 + customHeader = parseJsonObj(customHeader); + customBody = parseJsonObj(customBody); const data = { model, @@ -316,8 +318,8 @@ const genGemini = ({ .replaceAll(INPUT_PLACE_TO, to) .replaceAll(INPUT_PLACE_TEXT, text); - customHeader = JSON.parse("{" + customHeader + "}"); - customBody = JSON.parse("{" + customBody + "}"); + customHeader = parseJsonObj(customHeader); + customBody = parseJsonObj(customBody); const data = { system_instruction: { @@ -375,8 +377,8 @@ const genGemini2 = ({ .replaceAll(INPUT_PLACE_TO, to) .replaceAll(INPUT_PLACE_TEXT, text); - customHeader = JSON.parse("{" + customHeader + "}"); - customBody = JSON.parse("{" + customBody + "}"); + customHeader = parseJsonObj(customHeader); + customBody = parseJsonObj(customBody); const data = { model, @@ -431,8 +433,8 @@ const genClaude = ({ .replaceAll(INPUT_PLACE_TO, to) .replaceAll(INPUT_PLACE_TEXT, text); - customHeader = JSON.parse("{" + customHeader + "}"); - customBody = JSON.parse("{" + customBody + "}"); + customHeader = parseJsonObj(customHeader); + customBody = parseJsonObj(customBody); const data = { model, @@ -485,8 +487,8 @@ const genOllama = ({ .replaceAll(INPUT_PLACE_TO, to) .replaceAll(INPUT_PLACE_TEXT, text); - customHeader = JSON.parse("{" + customHeader + "}"); - customBody = JSON.parse("{" + customBody + "}"); + customHeader = parseJsonObj(customHeader); + customBody = parseJsonObj(customBody); const data = { model, diff --git a/src/libs/utils.js b/src/libs/utils.js index 9be0de5..12bd3f6 100644 --- a/src/libs/utils.js +++ b/src/libs/utils.js @@ -267,3 +267,25 @@ export const getHtmlText = (htmlStr, skipTag = "") => { return doc.body.innerText.trim(); }; + +/** + * 解析JSON字符串对象 + * @param {*} str + * @returns + */ +export const parseJsonObj = (str) => { + if (!str || type(str) !== "string") { + return {}; + } + + try { + if (str.trim()[0] !== "{") { + str = `{${str}}`; + } + return JSON.parse(str); + } catch (err) { + // + } + + return {}; +};