The Crystal Programming Language Forum

Jbuilder: an easy-to-use json builder in Crystal

Hi, everyone, I make a shard called Jbuilder, you can use it to render json in your web project. :grinning:

Example

require "jbuilder"

Jbuilder.new do |json|
  json.null nil
  json.code 200
  json.msg "ok"
  json.merge!({"code" => 201})
  json.array! "array1", [1, 1.0, "1"]
  json.array!("array2", [1, 2, 3, 4]) do |json, item|
    json.code item
  end
  json.data do |json|
    json.code 400
    json.array! "array3", [1, 1.0, "1"]
  end
  json.set!("custom_field", %w[1 2])
end.to_json

Features

  1. Plain Crystal.
  2. Take json as view.
  3. Support layout.
  4. Support partial.
  5. Support cache by import other shard.
  6. Support Kemal, Amber, Lucky, Runcobo, etc.

An example using Runcobo

   # Renders Jbuilder with "application/json" Content-Type.
    #
    # `src/views/layouts/application.jbuilder` must be present.
    # `src/views/renders/example.jbuilder` must be present.
    # ```
    # class RenderJbuilder < BaseAction
    #   layout "application"
    #
    #   call do
    #     render_jbuilder "renders/example", status_code: 200
    #   end
    # end
    # ```
    macro render_jbuilder(filename, *, layout = "", status_code = 200, dir = "src/views/", layout_dir = "src/views/layouts/")
      @context.response.content_type = "application/json"
      @context.response.status_code = {{ status_code }}
      {% layout_file = layout == "" ? LAYOUT : layout %}
      {% if layout_file == "" %}
        Jbuilder.embed("{{dir.id}}{{filename.id}}.jbuilder", @context.response.output)
      {% else %}
        Jbuilder.embed("{{dir.id}}{{filename.id}}.jbuilder", @context.response.output, "{{layout_dir.id}}{{layout_file.id}}.jbuilder")
      {% end %}
      @context
    end
2 Likes