DEV Community

Mehran Davoudi
Mehran Davoudi

Posted on

Parse OpenAI answers as JSON

Certainly! Here's a revised version of your blog post that is concise, simple, and friendly:


Working with OpenAI can be tricky when it comes to parsing JSON responses, especially when they include extra characters like ''' or a leading json:. To tackle this, I've developed PowerParseJson<T>(), a handy tool that simplifies the process.

var result = await client.GetChatCompletionsAsync(chatCompletionsOptions);
string answer = result.Value.Choices.FirstOrDefault()?.Message.Content;

// No more exceptions!
var json = SemanticUtils.PowerParseJson<JsonObject>(answer);
Enter fullscreen mode Exit fullscreen mode

You can find PowerParseJson<T>() on my GitHub: mehrandvd/SemanticValidation. It is also available here as a Nuget package: SemanticValidation Nuget

While newer GPT models offer settings for cleaner JSON outputs, many models still lack this feature. PowerParseJson<T>() is here to bridge that gap and make your OpenAI experience smoother.

Top comments (0)