优化 ExternalToolEditor 的 JSON 解析逻辑,支持更宽松的对象格式(如无引号键值对)
parent
bcb226c98b
commit
44dba476c4
|
|
@ -37,11 +37,11 @@ function parseJsonObject(value: string | undefined, fieldName: string, optional
|
|||
}
|
||||
|
||||
try {
|
||||
// 优先尝试标准 JSON 解析
|
||||
// 1. 优先尝试标准 JSON 解析
|
||||
return JSON.parse(trimmedValue);
|
||||
} catch (e) {
|
||||
try {
|
||||
// 失败后尝试作为 JS 对象解析 (支持无引号、单引号等)
|
||||
// 2. 失败后尝试作为 JS 对象解析 (支持无引号键、单引号等)
|
||||
// eslint-disable-next-line no-new-func
|
||||
const parsed = new Function(`return (${trimmedValue})`)();
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
|
|
@ -49,6 +49,35 @@ function parseJsonObject(value: string | undefined, fieldName: string, optional
|
|||
}
|
||||
throw new Error();
|
||||
} catch (e2) {
|
||||
// 3. 尝试宽松解析 (处理类似 { Content-Type: application/json } 这种完全无引号的情况)
|
||||
try {
|
||||
const content = trimmedValue.replace(/^\{/, '').replace(/\}$/, '').trim();
|
||||
const result: Record<string, any> = {};
|
||||
const pairs = content.split(/[\n,]/);
|
||||
let hasValidPair = false;
|
||||
|
||||
for (let pair of pairs) {
|
||||
pair = pair.trim();
|
||||
if (!pair) continue;
|
||||
const colonIndex = pair.indexOf(':');
|
||||
if (colonIndex > 0) {
|
||||
const k = pair.substring(0, colonIndex).trim().replace(/^['"]|['"]$/g, '');
|
||||
const v = pair.substring(colonIndex + 1).trim().replace(/^['"]|['"]$/g, '');
|
||||
if (k) {
|
||||
let finalVal: any = v;
|
||||
if (v === 'true') finalVal = true;
|
||||
else if (v === 'false') finalVal = false;
|
||||
else if (v === 'null') finalVal = null;
|
||||
else if (!isNaN(Number(v)) && v !== '') finalVal = Number(v);
|
||||
result[k] = finalVal;
|
||||
hasValidPair = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hasValidPair) return result;
|
||||
} catch (e3) {
|
||||
// ignore and fall through to error
|
||||
}
|
||||
throw new Error(`${fieldName}格式不正确,请确保是有效的 JSON 或对象格式`);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue