Skip to content

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

# frozen_string_literal: true

# json-to-schema — JSON instance → draft-07 JSON Schema inferrer. Ruby 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_objects 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. Errors return through the
# result hash — never raises.
require 'json'

module JsonToSchema
  module_function

  DRAFT_07 = 'http://json-schema.org/draft-07/schema#'

  ESCAPES = { '"' => '\\"', '\\' => '\\\\', "\b" => '\\b', "\f" => '\\f',
              "\n" => '\\n', "\r" => '\\r', "\t" => '\\t' }.freeze

  def scalar_kind(v)
    case v
    when TrueClass, FalseClass then 'boolean'
    when NilClass then 'null'
    when Integer then 'integer'
    when Float
      # JSON has no int type: an integral double (2.0, 1e2) is an integer.
      v.finite? && v == v.floor ? 'integer' : 'number'
    when Array then 'array'
    when Hash then 'object'
    else 'string'
    end
  end

  def array_items(v)
    kinds = v.map { |el| scalar_kind(el) }.uniq.sort
    kinds.length == 1 ? { 'type' => kinds[0] } : { 'type' => kinds }
  end

  def infer(v, strict)
    case v
    when Array
      return { 'type' => 'array' } if v.empty? # carries no `items` key
      { 'type' => 'array', 'items' => array_items(v) }
    when Hash
      keys = v.keys.sort
      properties = keys.each_with_object({}) { |k, h| h[k] = infer(v[k], strict) }
      schema = { 'type' => 'object', 'properties' => properties, 'required' => keys }
      schema['additionalProperties'] = false if strict
      schema
    else
      { 'type' => scalar_kind(v) }
    end
  end

  # JSON.stringify(value, null, 2) parity: 2-space indent, no HTML or unicode
  # escaping, control chars as lowercase \u00xx, empty containers collapsed.
  def dump_string(s)
    out = +'"'
    s.each_char do |c|
      out << (ESCAPES[c] || (c.ord < 0x20 ? format('\\u%04x', c.ord) : c))
    end
    out << '"'
  end

  def dump(v, indent)
    pad = '  ' * indent
    case v
    when Hash
      return '{}' if v.empty?
      entries = v.map { |k, el| "#{pad}  #{dump_string(k)}: #{dump(el, indent + 1)}" }
      "{\n#{entries.join(",\n")}\n#{pad}}"
    when Array
      return '[]' if v.empty?
      entries = v.map { |el| "#{pad}  #{dump(el, indent + 1)}" }
      "[\n#{entries.join(",\n")}\n#{pad}]"
    when String then dump_string(v)
    when true then 'true'
    when false then 'false'
    else 'null'
    end
  end

  def json_to_schema(raw, strict_objects: false)
    text = raw.strip
    return { output: '', error: nil } if text.empty? # NOT an error
    begin
      value = JSON.parse(text, quirks_mode: true) # allow scalar top level
    rescue JSON::ParserError => e
      return { output: '', error: e.message }
    end
    schema = { '$schema' => DRAFT_07 }
    schema.update(infer(value, strict_objects == true))
    { output: dump(schema, 0), error: nil }
  end
end

# Example:
# JsonToSchema.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 →