Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle invalid json #3258

Merged
merged 5 commits into from
Feb 5, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Making the closing quote optional with "? could allow the regex to match incomplete JSON values. For example, "name": "John would match, even though it's missing the closing quote. This creates a risk of silently accepting malformed data. Consider keeping the strict quote requirement and adding explicit error handling to provide better feedback when the JSON is invalid.

Spotted by Graphite Reviewer

Is this helpful? React 👍 or 👎 to let us know.

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
Loading