Transform a Dry::Struct into a JSON structure

Imagine we have this Struct

class Test < Dry::Struct
  attribute :resource_type, Dry.Types::String
  attribute :things, Dry.Types::Array do
    attribute :name, Dry.Types::String
  end
  attribute :other_things, Dry.Types::Hash do
    attribute :name, Dry.Types::String.optional.default(nil)
  end
end

How can I dynamically transform it into

{
  "resource_type": "string",
  "things": [
    {
      "name": "string"
    }
  ],
  "other_things": {
    "name": "string"
  }
}

The main issue I’m facing is that there are times where the type is complex (i.e. Dry::Types::Sum) and it’s very awkward to code all those different types. I mean, I don’t care if they’re optional or nil by default, I just want to know their type and put that directly in the json structure

What you are looking to do is transform the struct’s schema into an alternate data structure.

This can be done, but it’s not easy. You will need to convert the schema into its AST representation and then write a custom compiler to transform it.