Skip to content

devlooped/json5

Icon Json5

Version Downloads EULA License

Open Source Maintenance Fee

To ensure the long-term sustainability of this project, users of this package who generate revenue must pay an Open Source Maintenance Fee. While the source code is freely available under the terms of the License, this package and other aspects of the project require adherence to the Maintenance Fee.

To pay the Maintenance Fee, become a Sponsor at the proper OSMF tier. A single fee covers all of Devlooped packages.

A JSON5 parser for .NET built entirely on top of the public System.Text.Json API surface. Requires .NET 10+.

Usage

Parse to JsonNode

using Json5;

JsonNode? node = Json5.Parse("""
    {
        // comments are allowed
        unquoted: 'single-quoted string',
        hex: 0xDECAF,
        leadingDot: .5,
        trailing: 'comma',
    }
    """);

Deserialize to a typed object

var config = Json5.Deserialize<AppConfig>(json5String);

Parse to JsonDocument

using var doc = Json5.ParseDocument(json5String);
JsonElement root = doc.RootElement;

Convert to standard JSON

string json = Json5.ToJson(json5String);
byte[] utf8 = Json5.ToUtf8Json(json5Bytes);

Write to Utf8JsonWriter

Json5.WriteTo(json5String, writer);

JSON5 Features

All JSON5 extensions beyond standard JSON are supported:

Feature Example
Unquoted object keys { foo: 1 }
Single-quoted strings 'hello'
Multi-line strings (escaped newlines) 'line1\↵line2'
Hexadecimal numbers 0xFF
Leading/trailing decimal points .5, 2.
Explicit positive sign +1
Infinity, -Infinity, NaN Infinity
Single and multi-line comments // … and /* … */
Trailing commas [1, 2,]
Additional escape sequences \v, \0, \xHH
Extended whitespace Unicode Zs category, BOM

Auto-Dedent Multi-line Strings

When parsing multi-line string values, you can automatically remove common leading whitespace via Json5ReaderOptions.AutoDedent. This makes it easier to write readable indented code without the indentation appearing in the final string value.

var options = new Json5ReaderOptions { AutoDedent = true };
var node = Json5.Parse("""
    {
        description: '
            This is a multi-line string
            with consistent indentation
            that will be removed.
        '
    }
    """, options);
// description will be: "This is a multi-line string\nwith consistent indentation\nthat will be removed."

The algorithm:

  1. Strips the first line if blank
  2. Strips the last line if blank
  3. Finds the minimum common leading whitespace across all remaining non-blank lines
  4. Removes that minimum indent from every line

Only string values are affected; property names are never dedented. Blank lines within the string are preserved.

Infinity / NaN Handling

Since standard JSON has no representation for Infinity and NaN, the behavior is configurable via Json5ReaderOptions.SpecialNumbers:

Mode Behavior
AsString (default) Emits as "Infinity", "-Infinity", or "NaN"
AsNull Emits as null
Throw Throws Json5Exception
var options = new Json5ReaderOptions 
{ 
    SpecialNumbers = SpecialNumberHandling.AsNull 
};
var node = Json5.Parse("Infinity", options); // returns null

Icon Json5.Configuration

Version Downloads

The Json5.Configuration package integrates JSON5 files with the Microsoft.Extensions.Configuration infrastructure, so you can use JSON5 anywhere standard JSON configuration is used.

AddJson5File

using Json5;

var config = new ConfigurationBuilder()
    .AddJson5File("appsettings.json5")
    .AddJson5File("appsettings.Development.json5", optional: true, reloadOnChange: true)
    .Build();

The file supports all JSON5 extensions — comments, trailing commas, unquoted keys, etc.:

// appsettings.json5
{
    Logging: {
        LogLevel: {
            Default: "Information",
            // Silence noisy namespaces
            "Microsoft.AspNetCore": "Warning",
        },
    },
    ConnectionStrings: {
        Default: "Server=localhost;Database=MyApp",
    },
}

AddJson5Stream

using Json5;

using var stream = File.OpenRead("config.json5");

var config = new ConfigurationBuilder()
    .AddJson5Stream(stream)
    .Build();

Json5ReaderOptions

Pass Json5ReaderOptions via the source action to control special number handling, max depth, and auto-dedent:

var config = new ConfigurationBuilder()
    .AddJson5File(source =>
    {
        source.Path = "appsettings.json5";
        source.Optional = true;
        source.ReloadOnChange = true;
        source.Json5ReaderOptions = new Json5ReaderOptions
        {
            AutoDedent = true,
            SpecialNumbers = SpecialNumberHandling.AsNull
        };
    })
    .Build();

Sponsors

Clarius Org MFB Technologies, Inc. Khamza Davletov SandRock DRIVE.NET, Inc. Keith Pickford Thomas Bolon Kori Francis Uno Platform Reuben Swartz Jacob Foshee Eric Johnson Jonathan Ken Bonny Simon Cropp agileworks-eu Zheyu Shen Vezel ChilliCream 4OTC domischell Adrian Alonso torutek mccaffers Seika Logiciel Andrew Grant Lars

Sponsor this project

Learn more about GitHub Sponsors

About

An implementation of the JSON5 specification for .NET on top of System.Text.Json

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Sponsor this project

 

Packages

 
 
 

Contributors