loading a json schema including fragments

In the end I had to do this myself. Since all the fragments are of the same format, the following was possible:

  def read_schema(filename)
    reader = JSON::Schema::Reader.new(
      accept_uri: false,
      accept_file: true
    )
    schema = reader.read("#{Rails.root}/lib/record_schemas/#{filename}").schema
    return schema unless schema.has_key?('properties')

    schema['properties'].each_key do |key|
      fragment = schema['properties'].dig(key, 'items')
      next unless fragment

      ref = fragment['$ref']
      next unless ref

      next unless ref.start_with?('fragments/')

      file, type = ref.split('#')

      unless schema.has_key?('definitions')
        schema['definitions'] = {}
      end
      schema['definitions'][type] = read_fragment(file, type)
      schema['properties'][key]['items']['$ref'] = "#/definitions/#{type}"
    end
    schema
  end

  def read_fragment(file, key)
    reader = JSON::Schema::Reader.new(
        accept_uri: false,
        accept_file: true
    )
    schema = reader.read("#{Rails.root}/lib/record_schemas/#{file}").schema
    schema['definitions'][key]
  end

This looks for any references to a fragment in a schema and, if it finds one, converts the reference to an internal one and loads the fragment’s definition into the schema.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top