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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

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

👋 Kindness is contagious

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

Okay