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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay