to_json snippets

How to customize to_json

Tagged rails, activerecord, to_json  Languages ruby
def to_json(options = {})
  if options.empty?
    super :only => [:id, :name]
  else
    super options
  end
end

Now post.to_json will only include the id and name attributes.

Note that for arrays of objects--at least with Rails 2.3.4--you need use the same parameters on the array.to_json method:

Post.all.to_json :only => [:id, :name]

How to implement to_json in Crystal lang

Tagged to_json, crystal  Languages crystal

Tested on version 0.19.4. This is an example of how to implement a generic to_json method in Crystal lang:

class Document
  def initialize
    @name = "xyz"
    ...
  end
  
  # Returns an array containing all instance variables. Implemented with a macro.
  def instance_vars
    {{
      @type.instance_vars.map do |var|
        [ var.name.stringify, var.id ]
      end
    }}
  end

  # Returns a JSON string containing all instance variables
  def to_json
    result = String.build do |io|
      JSON::PrettyWriter.new(io, indent: "  ").json_object do |object|
        instance_vars.each do |var|
          name, value = var
          case value
          when XML::Node
            # skip
          else
            object.field name, value
          end
        end
      end
    end
  end