Skip to content

.NET: add JsonFixer utility for repairing malformed LLM JSON output#6204

Open
hanhan761 wants to merge 1 commit into
microsoft:mainfrom
hanhan761:feat-6067-json-fixer
Open

.NET: add JsonFixer utility for repairing malformed LLM JSON output#6204
hanhan761 wants to merge 1 commit into
microsoft:mainfrom
hanhan761:feat-6067-json-fixer

Conversation

@hanhan761
Copy link
Copy Markdown

Fixes #6067

Adds a utility class that automatically fixes common JSON malformations
that LLMs can produce, including:
- Markdown code fences wrapping JSON (`json ... `)
- Trailing commas before closing braces/brackets
- Truncated output (missing closing brackets, braces, or quotes)
- Stringified nested JSON objects

Fixes microsoft#6067
Copilot AI review requested due to automatic review settings May 30, 2026 07:27
@moonbox3 moonbox3 added the .NET label May 30, 2026
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Adds an internal JsonFixer utility for repairing common malformations in JSON returned by LLMs (markdown fences, trailing commas, truncation, stringified nested JSON), with accompanying unit tests.

Changes:

  • New JsonFixer static class with TryFix plus four discrete helpers.
  • Unit tests covering fence stripping, trailing commas, truncation completion, and combined scenarios.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 5 comments.

File Description
dotnet/src/Microsoft.Agents.AI/JsonFixer.cs New utility implementing JSON repair heuristics.
dotnet/tests/Microsoft.Agents.AI.UnitTests/JsonFixerTests.cs Unit tests for the new utility (no coverage for TryUnstringifyNestedJson).

// Match pattern: "propertyName": "{...}" or "propertyName": "{\\...}"
text = Regex.Replace(
text,
@"\""(\w+)\\"":\s*\""(\{.*?\})\""",
Comment on lines +188 to +189
// Unescape the string
potentialJson = Regex.Unescape(potentialJson);
Comment on lines +86 to +90
// Remove trailing comma before closing brace/bracket
text = Regex.Replace(text, @",(\s*[}\]])", "$1");

// Remove trailing comma at end of string (truncated after comma)
text = Regex.Replace(text, @",\s*$", "");
Comment on lines +63 to +64
// Find closing fence
int closeFence = text.LastIndexOf(FenceMarker, StringComparison.Ordinal);
Assert.Equal(expected, text);
}

// ---------- Combined TryFix ----------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

.NET: [Feature]: Automatically fix malformed JSON responses from LLMs

3 participants