Skip to content

JSON to JSON Schema Generator — PHP 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 PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.

<?php
// json-to-schema — JSON instance → draft-07 JSON Schema inferrer. PHP 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 strictObjects 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. Output is a hand-rolled 2-space pretty print
// with JSON.stringify(schema, null, 2) parity. Never throws — errors travel
// in the result array.

const JSON_TO_SCHEMA_DRAFT_07 = 'http://json-schema.org/draft-07/schema#';

function json_to_schema_scalar_kind($v): string
{
    if (is_bool($v)) return 'boolean';
    if ($v === null) return 'null';
    if (is_int($v)) return 'integer';
    if (is_float($v)) {
        // JSON has no int type: an integral double (2.0, 1e2) is an integer.
        return is_finite($v) && floor($v) === $v ? 'integer' : 'number';
    }
    if (is_array($v)) return 'array';
    if ($v instanceof stdClass) return 'object';
    return 'string';
}

/** Union of element kinds: one kind keeps it, else a sorted type list. */
function json_to_schema_array_items(array $v): array
{
    $types = array_values(array_unique(array_map('json_to_schema_scalar_kind', $v)));
    sort($types, SORT_STRING);
    return count($types) === 1 ? ['type' => $types[0]] : ['type' => $types];
}

function json_to_schema_infer($v, bool $strict)
{
    if (is_array($v)) {
        if ($v === []) return ['type' => 'array']; // carries no `items` key
        return ['type' => 'array', 'items' => json_to_schema_array_items($v)];
    }
    if ($v instanceof stdClass) {
        $keys = array_map('strval', array_keys(get_object_vars($v)));
        sort($keys, SORT_STRING);
        // stdClass keeps properties a map even when empty ({} not []).
        $properties = new stdClass();
        foreach ($keys as $k) {
            $properties->{$k} = json_to_schema_infer($v->$k, $strict);
        }
        $schema = ['type' => 'object', 'properties' => $properties, 'required' => $keys];
        if ($strict) $schema['additionalProperties'] = false;
        return $schema;
    }
    return ['type' => json_to_schema_scalar_kind($v)];
}

/** JSON.stringify escaping: control chars as lowercase \u00xx, no slash or
 *  unicode escaping. Bytes >= 0x20 pass through raw (valid UTF-8 stays). */
function json_to_schema_dump_string(string $s): string
{
    $out = '"';
    foreach (str_split($s, 1) as $ch) {
        $ord = ord($ch);
        if ($ord === 34) $out .= '\"';
        elseif ($ord === 92) $out .= '\\\\';
        elseif ($ord === 8) $out .= '\\b';
        elseif ($ord === 9) $out .= '\\t';
        elseif ($ord === 10) $out .= '\\n';
        elseif ($ord === 12) $out .= '\\f';
        elseif ($ord === 13) $out .= '\\r';
        elseif ($ord < 32) $out .= sprintf('\u%04x', $ord);
        else $out .= $ch;
    }
    return $out . '"';
}

/** 2-space pretty print with JSON.stringify(value, null, 2) parity. */
function json_to_schema_dump($v, int $indent): string
{
    $pad = str_repeat('  ', $indent);
    $inner = $pad . '  ';
    if (is_array($v)) { // list node (required, …)
        if ($v === []) return '[]';
        $entries = [];
        foreach ($v as $el) $entries[] = $inner . json_to_schema_dump($el, $indent + 1);
        return "[\n" . implode(",\n", $entries) . "\n" . $pad . ']';
    }
    if ($v instanceof stdClass) { // object node (properties, …)
        $vars = get_object_vars($v);
        if ($vars === []) return '{}';
        $entries = [];
        foreach ($vars as $k => $el) {
            $entries[] = $inner . json_to_schema_dump_string((string) $k) . ': '
                . json_to_schema_dump($el, $indent + 1);
        }
        return "{\n" . implode(",\n", $entries) . "\n" . $pad . '}';
    }
    if (is_bool($v)) return $v ? 'true' : 'false';
    if ($v === null) return 'null';
    return json_to_schema_dump_string((string) $v);
}

/**
 * Infer a draft-07 schema for the given JSON text.
 * @return array{output: string, error: string|null}
 */
function json_to_schema(string $raw, bool $strict_objects = false): array
{
    $text = trim($raw);
    if ($text === '') return ['output' => '', 'error' => null]; // NOT an error
    try {
        // assoc=false keeps objects stdClass so {} and [] stay distinct.
        $value = json_decode($text, false, 512, JSON_THROW_ON_ERROR);
    } catch (JsonException $e) {
        return ['output' => '', 'error' => $e->getMessage()];
    }
    $schema = ['$schema' => JSON_TO_SCHEMA_DRAFT_07];
    $schema += json_to_schema_infer($value, $strict_objects === true);
    return ['output' => json_to_schema_dump($schema, 0), 'error' => null];
}

// Example:
// json_to_schema('{"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 →