A utility to repair invalid JSON documents
$ dotnet add package JsonRepairUtilsJsonRepairUtils is a near-literal translation of the TypeScript JsonRepair library, see https://github.com/josdejong/jsonrepair
The jsonrepair library is basically an extended JSON parser. It parses the provided JSON document character by character. When it encounters a non-valid JSON structures it wil look to see it it can reconstruct the intended JSON. For example, after encountering an opening bracket {, it expects a key wrapped in double quotes. When it encounters a key without quotes, or wrapped in other quote characters, it will change these to double quotes instead.
The library has many uses, such as:
The library can fix the following issues:
“...” with regular double quotesNone, True, and False with null, true, and false/* ... */ and // ...callback({ ... }){\"stringified\": \"content\"}NumberLong(2) and ISODate("2012-12-19T06:01:17.171Z")"long text" + "more text on next line"{ "id": 1, "name": "John" }
{ "id": 2, "name": "Sarah" }
Use the original typescript version in a full-fledged application: https://jsoneditoronline.org Read the background article "How to fix JSON and validate it with ease"
var jsonRepair = JsonRepair();
// Enable throwing exceptions when JSON code can not be repaired or even understood (enabled by default)
jsonRepair.ThrowExceptions = true;
try
{
// The following is invalid JSON: is consists of JSON contents copied from
// a JavaScript code base, where the keys are missing double quotes,
// and strings are using single quotes:
string json = "{name: 'John'}";
string repaired = jsonRepair.Repair(json);
Console.WriteLine(repaired);
// Output: {"name": "John"}
}
catch (JsonRepairError err)
{
Console.WriteLine(err.Message);
Console.WriteLine("Position: " + err.Data["Position"]);
}
Similar libraries:
Thanks go out to Jos de Jong, who not only did all the heavy lifting in the original jsonrepair for typescript library, but also patiently helped getting this port to pass all unit tests.
Released under the MITS license.