JSON to JSON Schema Generator — C# source
Infer a draft-07 JSON Schema from any JSON document: scalar types, array item merging, all-keys-required objects and an optional strict mode. Runs locally in your browser with a shareable link.
This is the C# implementation — the same logic the interactive tool runs, in a shareable, citable form.
// json-to-schema — JSON instance → draft-07 JSON Schema inferrer. C# port
// (canonical TS: src/lib/json-to-schema.ts; Go twin: cli/json-to-schema).
// Given one JSON instance, infers a draft-07 style schema: the integer vs
// number split (2.0 is an integer — JSON has no int type), objects list every
// key as required with keys sorted, homogeneous arrays merge to a single item
// type, mixed arrays become a sorted `type` array (other keywords dropped),
// empty arrays carry no `items` key, and strict mode adds
// "additionalProperties": false to every object schema. Empty or
// whitespace-only input yields empty output, not an error; parse failures
// surface the parser's message via Result.Error. Output is a hand-rolled
// 2-space pretty print with JSON.stringify(schema, null, 2) parity.
using System;
using System.Collections.Generic;
using System.Text.Json;
public static class JsonToSchema
{
private const string Draft07 = "http://json-schema.org/draft-07/schema#";
/// Options: StrictObjects emits "additionalProperties": false on every
/// object schema (default false — objects stay open).
public sealed class Options
{
public bool StrictObjects { get; set; }
}
/// Result union mirror: Output + nullable Error (null on success).
public sealed class Result
{
public string Output { get; set; } = "";
public string Error { get; set; }
}
/// Infer a draft-07 schema for the given JSON text, pretty-printed 2-space.
public static Result ToSchema(string raw, Options options = null)
{
var res = new Result();
string text = raw == null ? "" : raw.Trim();
if (text.Length == 0) return res; // empty input is NOT an error
JsonElement value;
try
{
using var doc = JsonDocument.Parse(text, new JsonDocumentOptions
{
MaxDepth = 1024, // far past JSON.parse's practical stack limit
});
value = doc.RootElement.Clone();
}
catch (JsonException e)
{
res.Error = e.Message;
return res;
}
var root = new List<KeyValuePair<string, object>>
{
new("$schema", Draft07),
};
foreach (var kv in Infer(value, options != null && options.StrictObjects))
root.Add(kv);
res.Output = Dump(root, 0);
return res;
}
// ---- schema inference ----
private static string ScalarKind(JsonElement v)
{
switch (v.ValueKind)
{
case JsonValueKind.Array: return "array";
case JsonValueKind.Null: return "null";
case JsonValueKind.True:
case JsonValueKind.False: return "boolean";
case JsonValueKind.Number:
// JSON has no int type: an integral double (2.0, 1e2) is an
// integer. Non-finite overflow (1e400) stays "number", like
// JS's Infinity.
double d = v.GetDouble();
return !double.IsFinite(d) || d != Math.Floor(d) ? "number" : "integer";
case JsonValueKind.Object: return "object";
default: return "string";
}
}
private static List<KeyValuePair<string, object>> ScalarSchema(string type) =>
new List<KeyValuePair<string, object>> { new("type", type) };
// Sorted unique type list for a merged schema.
private static List<string> SortedKinds(JsonElement arr)
{
var kinds = new List<string>();
foreach (var el in arr.EnumerateArray())
{
string k = ScalarKind(el);
if (!kinds.Contains(k)) kinds.Add(k);
}
kinds.Sort(StringComparer.Ordinal); // code-unit order, like JS default sort
return kinds;
}
// Object nodes are List<KeyValuePair<string, object>> (insertion order
// preserved); list nodes are List<object>; leaves are string/bool.
private static List<KeyValuePair<string, object>> Infer(JsonElement v, bool strict)
{
if (v.ValueKind == JsonValueKind.Array)
{
if (v.GetArrayLength() == 0) return ScalarSchema("array"); // no `items` key
var items = ScalarSchema("array");
List<string> types = SortedKinds(v);
object typeNode = types.Count == 1
? (object)types[0]
: types.ConvertAll(t => (object)t);
items.Add(new KeyValuePair<string, object>("items", typeNode));
return items;
}
if (v.ValueKind == JsonValueKind.Object)
{
var entries = new List<KeyValuePair<string, JsonElement>>();
foreach (var prop in v.EnumerateObject())
{
// duplicate key: last wins, like JSON.parse
int found = entries.FindIndex(e => e.Key == prop.Name);
if (found >= 0) entries[found] = new KeyValuePair<string, JsonElement>(prop.Name, prop.Value.Clone());
else entries.Add(new KeyValuePair<string, JsonElement>(prop.Name, prop.Value.Clone()));
}
var keys = entries.ConvertAll(e => e.Key);
keys.Sort(StringComparer.Ordinal);
var properties = new List<KeyValuePair<string, object>>();
foreach (string k in keys)
{
JsonElement val = entries.Find(e => e.Key == k).Value;
properties.Add(new KeyValuePair<string, object>(k, Infer(val, strict)));
}
var schema = new List<KeyValuePair<string, object>>
{
new("type", "object"),
new("properties", properties),
new("required", keys.ConvertAll(k => (object)k)), // plain string list
};
if (strict) schema.Add(new KeyValuePair<string, object>("additionalProperties", false));
return schema;
}
return ScalarSchema(ScalarKind(v));
}
// ---- 2-space pretty printer (JSON.stringify(v, null, 2) parity) ----
private static string DumpString(string s)
{
var sb = new System.Text.StringBuilder("\"");
foreach (char c in s)
{
switch (c)
{
case '"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '\b': sb.Append("\\b"); break;
case '\f': sb.Append("\\f"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < ' ')
sb.Append("\\u").Append(((int)c).ToString("x4")); // lowercase hex
else
sb.Append(c); // raw UTF-16 passes through, like JS
break;
}
}
sb.Append('"');
return sb.ToString();
}
private static string Dump(object v, int indent)
{
string pad = new string(' ', indent * 2);
if (v is List<KeyValuePair<string, object>> obj)
{
if (obj.Count == 0) return "{}";
var parts = new List<string>();
foreach (var kv in obj)
parts.Add(pad + " " + DumpString(kv.Key) + ": " + Dump(kv.Value, indent + 1));
return "{\n" + string.Join(",\n", parts) + "\n" + pad + "}";
}
if (v is List<object> list)
{
if (list.Count == 0) return "[]";
var parts = new List<string>();
foreach (var el in list)
parts.Add(pad + " " + Dump(el, indent + 1));
return "[\n" + string.Join(",\n", parts) + "\n" + pad + "]";
}
if (v is bool b) return b ? "true" : "false";
return DumpString(v as string ?? "");
}
}
// Example:
// JsonToSchema.ToSchema("{\"b\": 1, \"a\": [1, \"x\"]}").Output
// → {
// "$schema": "http://json-schema.org/draft-07/schema#",
// "type": "object",
// "properties": { "a": { "type": "array", "items": { "type": ["integer", "string"] } }, "b": { "type": "integer" } },
// "required": ["a", "b"]
// }
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 →