{"id":13878629,"url":"https://github.com/distil/jserializer","last_synced_at":"2026-03-08T13:36:27.137Z","repository":{"id":56879437,"uuid":"149126091","full_name":"distil/jserializer","owner":"distil","description":"A JSON Serializer for Ruby Objects","archived":false,"fork":false,"pushed_at":"2021-10-09T02:26:12.000Z","size":42,"stargazers_count":15,"open_issues_count":0,"forks_count":2,"subscribers_count":27,"default_branch":"master","last_synced_at":"2025-12-04T04:55:21.308Z","etag":null,"topics":["json","ruby"],"latest_commit_sha":null,"homepage":null,"language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/distil.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-09-17T13:03:13.000Z","updated_at":"2024-11-07T18:00:54.000Z","dependencies_parsed_at":"2022-08-20T22:31:25.863Z","dependency_job_id":null,"html_url":"https://github.com/distil/jserializer","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/distil/jserializer","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/distil%2Fjserializer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/distil%2Fjserializer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/distil%2Fjserializer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/distil%2Fjserializer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/distil","download_url":"https://codeload.github.com/distil/jserializer/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/distil%2Fjserializer/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30214830,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-07T12:15:00.571Z","status":"ssl_error","status_checked_at":"2026-03-07T12:15:00.217Z","response_time":53,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["json","ruby"],"created_at":"2024-08-06T08:01:55.207Z","updated_at":"2026-03-08T13:36:27.122Z","avatar_url":"https://github.com/distil.png","language":"Ruby","readme":"# JSerializer\n\n[![Build Status](https://travis-ci.org/distil/jserializer.svg)](https://travis-ci.org/distil/jserializer)\n[![Code Climate](https://codeclimate.com/github/distil/jserializer.svg)](https://codeclimate.com/github/distil/jserializer)\n\nJSerializer is a JSON Serializer for Ruby objects. It is designed to be a drop-in replacement of Active Model Serializer (target version: [0.8](https://github.com/rails-api/active_model_serializers/tree/0-8-stable)) with [better performance](benchmark/README.md).\n\nJSerializer does not rely on Rails or Active Model or Active Support, which makes it easier to be integrated into general Ruby projects.\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem 'jserializer'\n```\n\nAnd then execute:\n\n    $ bundle\n\nOr install it yourself as:\n\n    $ gem install jserializer\n\n## Usage\n\n### Define a Model\n```ruby\nPerson = Struct.new(:id, :first_name, :last_name, :age, :gender, :country)\n```\n\n### Create a Serializer\n```ruby\nclass PersonSerializer \u003c Jserializer::Base\n  root :user\n  attributes :full_name, :age, :gender\n  attribute :country, key: :country_code\n\n  def full_name\n    \"#{object.first_name} #{object.last_name}\"\n  end\n\n  def gender\n    object.gender == 'm' ? 'Male' : 'Female'\n  end\n\n  def include_age?\n    object.age \u003e= 18\n  end\nend\n```\n\n### Generate JSON\n```ruby\nperson = Person.new(1, 'John', 'Doe', 16, 'm', 'US')\nserializer = PersonSerializer.new(person)\n\n# generates a Hash without root key\n# =\u003e {:full_name=\u003e\"John Doe\", :gender=\u003e\"Male\", :country_code=\u003e\"US\"}\nserializer.serializable_hash\n\n# generates a Hash with root key\n# =\u003e {:user=\u003e{:full_name=\u003e\"John Doe\", :gender=\u003e\"Male\", :country_code=\u003e\"US\"}}\nserializer.as_json\n\n# generates JSON =\u003e {\"user\":{\"full_name\":\"John Doe\",\"gender\":\"Male\",\"country_code\":\"US\"}}\nserializer.to_json\n```\n\n### Generate JSON Collection\n```ruby\npersons = 2.times.map{|i| Person.new(i, 'Person', \"#{i}\", 17 + i, 'm', 'US') }\nserializer = PersonSerializer.new(persons, is_collection: true)\nserializer.to_json\n```\nYou will get:\n```json\n{\n  \"user\":[\n    {\n      \"full_name\":\"Person 0\",\n      \"gender\":\"Male\",\n      \"country_code\":\"US\"\n    },\n    {\n      \"full_name\":\"Person 1\",\n      \"age\":18,\n      \"gender\":\"Male\",\n      \"country_code\":\"US\"\n    }\n  ]\n}\n```\n\n### Bring Your Own JSON Encoder\nOur `to_json` method uses standard JSON module to generate JSON string. There are many JSON encode backend there, and they offer different customization options. Besides, you can use MultiJson to switch between different backends.\n\nYou are welcome to bring your own solution here. To do that, simply override the `to_json` method\n```ruby\nclass ApplicationSerializer \u003c Jserializer::Base\n  def to_json(*)\n    # use ActiveSupport in Rails as a delegator\n    ActiveSupport::JSON.encode(as_json)\n    # use oj:\n    # Oj.dump(as_json, mode: :compat, use_to_json: true)\n  end\nend\n```\nThen the rest of your serializers can inherit from `ApplicationSerializer` and start to use your preferred encoder.\n\n\n## Serializer Class Definition Options\n\nMethod       | Options       | Description\n------------ | ------------- | -------------\nroot | N/A | Set the root key of the generated JSON\nattributes | N/A | Define a list of fields separated by `,` to be exposed from a Ruby object\nattribute | :key - The name in the JSON output | Similar to `attributes` but for one field\nhas_many | :serializer\u003cbr\u003e :key\u003cbr\u003e :embed \u003cbr\u003e :embed_key\u003cbr\u003e | Include a collection of objects with has many association\nhas_one | Same as has_many | Include a object with has one association\nembed | :ids\u003cbr\u003e :objects | Determine if only include IDs of the associations\n\n### Example\nThis example shows you where to apply the above methods\n```ruby\nclass PostSerializer \u003c Jserializer::Base\n  root :article\n  embed :ids\n  attributes :id, :title, :content\n  attribute :writer, key: :written_by\n  has_many :comments, serializer: CommentSerializer, embed: :objects\n  has_one :author, serializer: AuthorSerializer, embed_key: :id\nend\n```\n\nFor associations, Jserializer uses the following ways to retrieve data:\n\nType | Method | Example |\n------------ | ------------- | -------------\n|  has_many | `collection_singular_ids`  | `posts` =\u003e `post_ids`|\n|  has_one |  `association.id` |  `account` =\u003e `account.id`  |\n\n\n## Initialization Options for Serializer Instance\n\n| Options       | Description\n| ------------- | -------------\nroot | Set the root key of the generated JSON, set it to `false` to disable\nmeta | Meta information to be included in the JSON output\nmeta_key | The key name of the meta information, the default is `:meta`\nis_collection | Whether the given object is a collection or single object\nonly | An array of attributes to be included in the JSON output\nexcept | An array of attributes to be excluded in the JSON output\ncurrent_user | Use for determine the authorization scope\n\n### Example\n```ruby\nPostSerializer.new(posts,\n                   root: :post,\n                   meta: { page: 1, total: 100},\n                   is_collection: true,\n                   only: [:title, :content])\n```\n\nYou can enable/disable root when initializing a serializer instance:\n```ruby\nPostSerializer.new(post, root: false)\n```\n\nOr when calling `as_json` method:\n```ruby\n# here the root option only accept a boolean value\n# you cannot rename root at this point\nPostSerializer.new(post).as_json(root: false)\n```\n\nYou can always get the Hash representation without `root` and `meta` information by calling `serializable_hash`\n```ruby\nPostSerializer.new(post).serializable_hash\n```\n\n### Collection\nThe `active_serializer_model` gem includes the `ArraySerializer` class to handle collections. There are a lot of magics happening underneath when you pass a collection object into `render json: @xxx`, to allow `ArraySerializer` gets triggered automatically.\n\nUnlike `active_serializer_model`, there is no separate serializer class for array. To serialize a collection, you need to set `is_collection: true` when initializing a new serializer\n```ruby\nserializer = PostSerializer.new(posts, is_collection: true)\nserializer.serializable_hash # or serializer.as_json to include root\n```\n\nYou can also call `serializable_collection` method directly which will ignore the `is_collection` option\n```ruby\nserializer = PostSerializer.new(posts)\nserializer.serializable_collection\n```\n\n\n## Compatibility \u0026 Migration\n\nCurrently, this gem is not compatible with `active_serializer_model` if you:\n- have `include_xxx?` as private method\n- override the instance method `attributes`\n- override any internal method `_xxx` (e.g. `_serializable_array`)\n- expect serializer to automatically include a root for you\n- expect serializer figures out if the object is a collection automatically\n\nSince we try to reuse serializer instances to avoid unnecessary object creations, make sure there is no things like `||=` in the serializer class. Or you can override `reset` method to clean things out\n```ruby\nclass MySerializer \u003c Jserializer::Base\n  ... ...\n  def reset(object)\n    @my_cached_stuff = nil\n    ... ...\n    super\n  end\n```\n\n### active_model_serializer method\nThis gem will try to find and use the serializer class defined by `active_model_serializer` method in a model, if you don't specify `serializer` explicitly\n\n```ruby\nclass Post \u003c ActiveRecord::Base\n  def active_model_serializer\n    MyPostSerializer\n  end\nend\n```\n\n### Use in Rails Action Controller\nActive Model Serializer overrides `render :json` in [ActionController::Serialization](https://github.com/rails-api/active_model_serializers/blob/0-8-stable/lib/action_controller/serialization.rb), which is convenient. But it touches Rails internal methods which could bring compatibility issues when upgrading Rails.\n\nThis gem does not provide such feature, but you can easily achieve it in application layer, for example, create a wrapper method for `render`:\n```ruby\nclass ApplicationController \u003c ActionController::Base\n  # ... ...\n  def render_json(resource, options = {})\n    if options.key?(:serializer)\n      serializer = options.delete(:serializer)\n    elsif options.key?(:each_serializer)\n      serializer = options.delete(:each_serializer)\n      options[:is_collection] = true\n    end\n\n    if !serializer \u0026\u0026 resource.respond_to?(:active_model_serializer)\n      serializer = resource.active_model_serializer\n    end\n\n    if serializer\n      options[:scope] = current_user\n      options[:json] = serializer.new(resource, options)\n    else\n      options[:json] = resource\n    end\n    render options\n  end\nend\n```\nThen you can use this `render_json` method whenever you need to call `render json: resource ...` in your controllers. And this is probably a good way to migrate gradually.\n\n### Caching\nThis gem does not plan to implement the cache feature.\n\n\n## Benchmark\n[See here](benchmark/README.md)\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at https://github.com/distil/jserializer.\n","funding_links":[],"categories":["Ruby"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdistil%2Fjserializer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdistil%2Fjserializer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdistil%2Fjserializer/lists"}