Skip to content

JSON Schema Validator — Ruby source

Validate a JSON document against a draft-07 subset schema: types, required, bounds, patterns, enums, arrays and strict objects, every issue reported at its exact path. Pairs with the schema generator. Runs locally with a shareable link.

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

# json-schema-validator — draft-07 SUBSET JSON Schema validator. Ruby port
# (canonical TS: src/lib/json-schema-validator.ts; Go twin:
# cli/json-schema-validator). Validates a JSON instance against a schema
# supporting: type (string or array, "integer" counts as "number"), enum,
# const, minimum/maximum/exclusiveMinimum/exclusiveMaximum, minLength/
# maxLength (TS .length counts UTF-16 code units: astral chars are 2),
# pattern, minItems/maxItems, uniqueItems, items, required, properties,
# additionalProperties: false, and the boolean schemas true/false.
# Unsupported keywords ($ref/$defs, oneOf/anyOf/allOf/not, patternProperties,
# dependencies, format, propertyNames, contains) are ignored, exactly like
# the TS lib and the Go twin; the companion generator (json-to-schema) never
# emits any of them. Numbers print into messages with JS Number-to-string
# rules (70000, 1.5e-7, 1e+21). Hash iteration order (insertion) drives
# issue ordering. Never raises — errors travel in the result hash.
require 'json'

module JsonSchemaValidator
  module_function

  def kind_of(v)
    case v
    when true, false then 'boolean'
    when nil then 'null'
    when Integer then 'integer'
    when Float then v.finite? && v == v.floor ? 'integer' : 'number'
    when Array then 'array'
    when Hash then 'object'
    else 'string'
    end
  end

  def deep_equal(a, b)
    return false if kind_of(a) != kind_of(b)
    case kind_of(a)
    when 'array'
      a.length == b.length && a.each_with_index.all? { |x, i| deep_equal(x, b[i]) }
    when 'object'
      a.length == b.length && a.all? { |k, val| b.key?(k) && deep_equal(val, b[k]) }
    else a == b
    end
  end

  # JS Number-to-string: plain integers below 1e21, exponential only past
  # the JS thresholds (decimal exponent < -6 or >= 21), minimal exponent
  # digits ('1.5e-7', '1e+21').
  def js_num(v)
    return v.to_s if v.is_a?(Integer)
    return 'NaN' if v.nan?
    return v.positive? ? 'Infinity' : '-Infinity' if v.infinite?
    return '0' if v.zero?
    neg = v.negative?
    a = v.abs
    return (neg ? '-' : '') + a.to_i.to_s if a == a.floor && a < 1e21
    text = a.to_s
    if text.include?('e')
      mant, exp_s = text.split('e')
      exp = exp_s.to_i
      digits = mant.delete('.')
    else
      intpart, frac = text.split('.')
      digits = intpart + frac
      exp = intpart.length - 1
      while digits.length > 1 && digits.start_with?('0')
        digits = digits[1..]
        exp -= 1
      end
    end
    if exp < -6 || exp >= 21
      head = digits[0] + (digits.length > 1 ? '.' + digits[1..] : '')
      return (neg ? '-' : '') + head + 'e' + (exp >= 0 ? '+' : '-') + exp.abs.to_s
    end
    return (neg ? '-' : '') + '0.' + '0' * (-exp - 1) + digits if exp < 0
    if digits.length > exp + 1
      return (neg ? '-' : '') + digits[0..exp] + '.' + digits[(exp + 1)..]
    end
    (neg ? '-' : '') + digits + '0' * (exp + 1 - digits.length)
  end

  # TS .length: UTF-16 code units — astral chars count as 2.
  def utf16_len(s)
    s.codepoints.sum { |cp| cp > 0xFFFF ? 2 : 1 }
  end

  # JS String(v) for schema type entries and required keys.
  def js_str(v)
    case v
    when nil then 'null'
    when true then 'true'
    when false then 'false'
    when Numeric then js_num(v)
    when String then v
    when Array then v.map { |x| js_str(x) }.join(',')
    else '[object Object]'
    end
  end

  def issue(out, path, message)
    out << { path: path, message: message }
  end

  def validate(v, schema, path, out)
    return if schema == true
    if schema == false
      issue(out, path, 'no value is allowed here (schema is false)')
      return
    end
    unless schema.is_a?(Hash)
      issue(out, path, 'invalid schema node: expected an object or boolean')
      return
    end

    if schema.key?('type')
      t = schema['type']
      allowed = t.is_a?(Array) ? t.map { |x| js_str(x) } : [js_str(t)]
      actual = kind_of(v)
      ok = allowed.any? { |x| x == actual || (x == 'number' && actual == 'integer') }
      issue(out, path, "expected type #{allowed.join('|')}, got #{actual}") unless ok
    end

    if schema.key?('enum')
      entries = schema['enum'].is_a?(Array) ? schema['enum'] : []
      issue(out, path, "value not in enum (#{entries.length} allowed)") unless entries.any? { |e| deep_equal(v, e) }
    end

    if schema.key?('const') && !deep_equal(v, schema['const'])
      issue(out, path, 'value does not match const')
    end

    if v.is_a?(Numeric)
      m = schema['minimum']
      issue(out, path, "#{js_num(v)} is less than minimum #{js_num(m)}") if m.is_a?(Numeric) && v < m
      m = schema['maximum']
      issue(out, path, "#{js_num(v)} is greater than maximum #{js_num(m)}") if m.is_a?(Numeric) && v > m
      m = schema['exclusiveMinimum']
      if m.is_a?(Numeric) && v <= m
        issue(out, path, "#{js_num(v)} is not greater than exclusiveMinimum #{js_num(m)}")
      end
      m = schema['exclusiveMaximum']
      if m.is_a?(Numeric) && v >= m
        issue(out, path, "#{js_num(v)} is not less than exclusiveMaximum #{js_num(m)}")
      end
    end

    if v.is_a?(String)
      n = utf16_len(v)
      m = schema['minLength']
      if m.is_a?(Numeric) && n < m
        issue(out, path, "string length #{n} is less than minLength #{js_num(m)}")
      end
      m = schema['maxLength']
      if m.is_a?(Numeric) && n > m
        issue(out, path, "string length #{n} is greater than maxLength #{js_num(m)}")
      end
      p = schema['pattern']
      if p.is_a?(String)
        begin
          ok = Regexp.new(p).match?(v)
        rescue RegexpError
          ok = nil
        end
        if ok.nil?
          issue(out, path, "invalid pattern in schema: #{p}")
        elsif !ok
          issue(out, path, "string does not match pattern #{p}")
        end
      end
    end

    if v.is_a?(Array)
      m = schema['minItems']
      if m.is_a?(Numeric) && v.length < m
        issue(out, path, "array length #{v.length} is less than minItems #{js_num(m)}")
      end
      m = schema['maxItems']
      if m.is_a?(Numeric) && v.length > m
        issue(out, path, "array length #{v.length} is greater than maxItems #{js_num(m)}")
      end
      if schema['uniqueItems'] == true
        (0...v.length).each do |i|
          ((i + 1)...v.length).each do |j|
            if deep_equal(v[i], v[j])
              issue(out, "#{path}[#{j}]", "duplicate item (same as index #{i})")
            end
          end
        end
      end
      if schema.key?('items')
        v.each_with_index { |item, i| validate(item, schema['items'], "#{path}[#{i}]", out) }
      end
    end

    if v.is_a?(Hash)
      req = schema['required']
      if req.is_a?(Array)
        req.each do |rk|
          key = js_str(rk)
          issue(out, path, "missing required property \"#{key}\"") unless v.key?(key)
        end
      end
      props = schema['properties'].is_a?(Hash) ? schema['properties'] : {}
      props.each do |key, sub|
        validate(v[key], sub, "#{path}.#{key}", out) if v.key?(key)
      end
      if schema['additionalProperties'] == false
        v.each_key do |key|
          issue(out, "#{path}.#{key}", 'additional property not allowed') unless props.key?(key)
        end
      end
    end
  end

  # Validate a JSON document against a schema. Returns
  # { valid:, issues: [{path:, message:}], error: } — error is nil when the
  # verdict is real (TS: error: null).
  def validate_json_schema(schema_raw, instance_raw)
    if schema_raw.strip.empty? || instance_raw.strip.empty?
      return { valid: false, issues: [], error: 'Both a schema and an instance are required' }
    end
    begin
      schema = JSON.parse(schema_raw, quirks_mode: true) # allow scalar top level
    rescue JSON::ParserError => e
      return { valid: false, issues: [], error: 'Schema: ' + (e.message.empty? ? 'Invalid JSON' : e.message) }
    end
    begin
      instance = JSON.parse(instance_raw, quirks_mode: true)
    rescue JSON::ParserError => e
      return { valid: false, issues: [], error: 'Instance: ' + (e.message.empty? ? 'Invalid JSON' : e.message) }
    end
    issues = []
    validate(instance, schema, '$', issues)
    issues.empty? ? { valid: true, issues: [], error: nil } : { valid: false, issues: issues, error: nil }
  end
end

# Example:
# JsonSchemaValidator.validate_json_schema(
#   '{"type":"object","required":["port"],"properties":{"port":{"type":"integer","minimum":1024}}}',
#   '{"port":80}')[:issues]
# → [{ path: '$.port', message: '80 is less than minimum 1024' }]

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 →