The Crystal Programming Language Forum

Writing Crystal classes/etc to file

I’m sure I saw a post asking about this.

Basically, for saving objects to files", you need:

  • require "json"
  • include ::JSON::Serializable (or yaml instead; likewise below)
  • def initialize(json_params)...
  • save/load via self.from_json(some_json_string) and self.to_json and save contents of to_json results to file, etc
  • Some things don’t serialize well (e.g.: Symbols), so find alternatives.
  • Performance Note: Writing to file will probably be slower than writing to memory.

See also: Carcin

require "json"

class Foo
  include ::JSON::Serializable # This along with `require "json"` enables `.from_json` and `.to_json` for many classes/structures.
    # Symbol don't serialize, but you can use Enum's like:
    enum Widget
      Alpha = 19
      Beta  = 28
      Gamma = 37

    getter bar : Widget

    def initialize(@bar = Widget::Beta)
    # You'll need an initialize that handles all serializable params to be saved/loaded via the json version.

# example usage:

foo = Foo::Widget::Gamma)

puts "foo: #{foo}"
puts "foo as json: #{foo.to_json}" # or print to file, etc

foo2 = Foo.from_json(foo.to_json)

puts "foo2: #{foo2}"
puts " #{}"
puts " as int: #{}"
puts "'s class: #{}"
puts "foo2 as json: #{foo2.to_json}"

2 posts were merged into an existing topic: Open, read and write binary into a file