Repairing Broken JSON from LLM Outputs: A Step-by-Step Guide

2 min read

When working with Large Language Models (LLMs), you might encounter broken JSON outputs that prevent you from parsing them correctly. In this article, I'll show you a simple step-by-step guide to repair broken JSON from LLM outputs.

The problem of broken JSON from LLMs is more common than you'd think. According to a recent article on Dev.to, "Your LLM returned broken JSON. Here is how to repair it before JSON.parse throws", many developers struggle with this issue. The article suggests that the problem is often caused by the LLM returning JSON with missing or extra characters, such as quotes or commas.

To repair broken JSON, you can use the json5 library in JavaScript. Here's a simple example:

javascript
const json5 = require('json5');

const brokenJson = '{"key": "value" }';
const repairedJson = json5.parse(brokenJson);

console.log(repairedJson);

This code uses the json5.parse() function to parse the broken JSON string. The json5 library is more flexible than the standard JSON.parse() function and can handle missing or extra characters in the JSON string.

Another solution is to use the quick-look library, which can also repair broken JSON. Here's an example:

javascript
const quickLook = require('quick-look');

const brokenJson = '{"key": "value" }';
const repairedJson = quickLook.parse(brokenJson);

console.log(repairedJson);

This code uses the quick-look.parse() function to parse the broken JSON string. The quick-look library is another option for repairing broken JSON, and it's often faster than the json5 library.

Try this

To try these solutions, you can install the json5 library using npm:

bash
npm install json5

Then, you can use the json5.parse() function to repair broken JSON strings.

Sources