Skip to content

JSON Validator — C# source

Validate JSON and pinpoint errors with line and column numbers. Clear valid/invalid verdict plus the exact error location - runs entirely in your browser.

This is the C# implementation — the same logic the interactive tool runs, in a shareable, citable form.

// json-validator — C# (.NET 8) port using System.Text.Json, ported from src/lib/jsonValidate.ts.
using System;
using System.Text.Json;

// Validate a JSON string. Never throws. Unlike the JS port (which scans the
// engine message for "at position N"), JsonException reports the exact
// 0-based line number and byte offset within the line — lifted to 1-based.
Result ValidateJson(string text)
{
    if (string.IsNullOrWhiteSpace(text))
        return new Result(false, "Input is empty", null, null);

    try
    {
        using var _ = JsonDocument.Parse(text);
        return new Result(true, null, null, null);
    }
    catch (JsonException ex)
    {
        int? line = ex.LineNumber is int ln ? ln + 1 : null;
        int? column = (int?)ex.BytePositionInLine is int col ? col + 1 : null;
        return new Result(false, ex.Message, line, column);
    }
}

// Demo: {"a": [1, 2, {"b": null}]} is valid; a stray comma is not.
foreach (var sample in new[] { """{"a": [1, 2, {"b": null}]}""", "{\n  \"a\": ,\n}" })
{
    var r = ValidateJson(sample);
    Console.WriteLine(r.Valid ? "valid" : $"invalid: {r.Error} (line {r.Line}, column {r.Column})");
}

// Mirrors the TypeScript result shape: null line/column = no position.
record Result(bool Valid, string? Error, int? Line, int? Column);

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →