Skip to content

Commit cbe6020

Browse files
authored
Merge pull request #3258 from elizaOS/tcm-handle-invalid-json
fix: handle invalid json
2 parents fd64139 + 7ee5834 commit cbe6020

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

packages/core/src/parsing.ts

+6-5
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ export function parseJSONObjectFromText(
146146
const jsonBlockMatch = text.match(jsonBlockPattern);
147147

148148
if (jsonBlockMatch) {
149-
const parsingText = normalizeJsonString(jsonBlockMatch[1]);
149+
const parsingText = normalizeJsonString(text);
150150
try {
151151
jsonData = JSON.parse(parsingText);
152152
} catch (e) {
@@ -155,11 +155,11 @@ export function parseJSONObjectFromText(
155155
return extractAttributes(text);
156156
}
157157
} else {
158-
const objectPattern = /{[\s\S]*?}/;
158+
const objectPattern = /{[\s\S]*?}?/;
159159
const objectMatch = text.match(objectPattern);
160160

161161
if (objectMatch) {
162-
const parsingText = normalizeJsonString(objectMatch[0]);
162+
const parsingText = normalizeJsonString(text);
163163
try {
164164
jsonData = JSON.parse(parsingText);
165165
} catch (e) {
@@ -193,19 +193,20 @@ export function extractAttributes(
193193
response: string,
194194
attributesToExtract?: string[]
195195
): { [key: string]: string | undefined } {
196+
response = response.trim();
196197
const attributes: { [key: string]: string | undefined } = {};
197198

198199
if (!attributesToExtract || attributesToExtract.length === 0) {
199200
// Extract all attributes if no specific attributes are provided
200-
const matches = response.matchAll(/"([^"]+)"\s*:\s*"([^"]*)"/g);
201+
const matches = response.matchAll(/"([^"]+)"\s*:\s*"([^"]*)"?/g);
201202
for (const match of matches) {
202203
attributes[match[1]] = match[2];
203204
}
204205
} else {
205206
// Extract only specified attributes
206207
attributesToExtract.forEach((attribute) => {
207208
const match = response.match(
208-
new RegExp(`"${attribute}"\\s*:\\s*"([^"]*)"`, "i")
209+
new RegExp(`"${attribute}"\\s*:\\s*"([^"]*)"?`, "i")
209210
);
210211
if (match) {
211212
attributes[attribute] = match[1];

0 commit comments

Comments
 (0)