Skip to content

Commit

Permalink
Merge pull request #3258 from elizaOS/tcm-handle-invalid-json
Browse files Browse the repository at this point in the history
fix: handle invalid json
  • Loading branch information
lalalune authored Feb 5, 2025
2 parents fd64139 + 7ee5834 commit cbe6020
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions packages/core/src/parsing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ export function parseJSONObjectFromText(
const jsonBlockMatch = text.match(jsonBlockPattern);

if (jsonBlockMatch) {
const parsingText = normalizeJsonString(jsonBlockMatch[1]);
const parsingText = normalizeJsonString(text);
try {
jsonData = JSON.parse(parsingText);
} catch (e) {
Expand All @@ -155,11 +155,11 @@ export function parseJSONObjectFromText(
return extractAttributes(text);
}
} else {
const objectPattern = /{[\s\S]*?}/;
const objectPattern = /{[\s\S]*?}?/;
const objectMatch = text.match(objectPattern);

if (objectMatch) {
const parsingText = normalizeJsonString(objectMatch[0]);
const parsingText = normalizeJsonString(text);
try {
jsonData = JSON.parse(parsingText);
} catch (e) {
Expand Down Expand Up @@ -193,19 +193,20 @@ export function extractAttributes(
response: string,
attributesToExtract?: string[]
): { [key: string]: string | undefined } {
response = response.trim();
const attributes: { [key: string]: string | undefined } = {};

if (!attributesToExtract || attributesToExtract.length === 0) {
// Extract all attributes if no specific attributes are provided
const matches = response.matchAll(/"([^"]+)"\s*:\s*"([^"]*)"/g);
const matches = response.matchAll(/"([^"]+)"\s*:\s*"([^"]*)"?/g);
for (const match of matches) {
attributes[match[1]] = match[2];
}
} else {
// Extract only specified attributes
attributesToExtract.forEach((attribute) => {
const match = response.match(
new RegExp(`"${attribute}"\\s*:\\s*"([^"]*)"`, "i")
new RegExp(`"${attribute}"\\s*:\\s*"([^"]*)"?`, "i")
);
if (match) {
attributes[attribute] = match[1];
Expand Down

0 comments on commit cbe6020

Please sign in to comment.