DEV Community

Mehran Davoudi
Mehran Davoudi

Posted on

5

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay