{"id":19744982,"url":"https://github.com/narazaka/json-schema-serializer","last_synced_at":"2025-07-28T00:32:40.957Z","repository":{"id":55499858,"uuid":"224380773","full_name":"Narazaka/json-schema-serializer","owner":"Narazaka","description":"JSON Schema based serializer for ruby","archived":false,"fork":false,"pushed_at":"2020-12-26T15:46:21.000Z","size":100,"stargazers_count":2,"open_issues_count":0,"forks_count":1,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-07-26T11:51:19.804Z","etag":null,"topics":["json","json-schema","ruby","serializer"],"latest_commit_sha":null,"homepage":null,"language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"zlib","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Narazaka.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","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":"2019-11-27T08:25:24.000Z","updated_at":"2020-12-26T15:46:23.000Z","dependencies_parsed_at":"2022-08-15T01:50:42.309Z","dependency_job_id":null,"html_url":"https://github.com/Narazaka/json-schema-serializer","commit_stats":null,"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"purl":"pkg:github/Narazaka/json-schema-serializer","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Narazaka%2Fjson-schema-serializer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Narazaka%2Fjson-schema-serializer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Narazaka%2Fjson-schema-serializer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Narazaka%2Fjson-schema-serializer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Narazaka","download_url":"https://codeload.github.com/Narazaka/json-schema-serializer/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Narazaka%2Fjson-schema-serializer/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":267446806,"owners_count":24088561,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-27T02:00:11.917Z","response_time":82,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"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","json-schema","ruby","serializer"],"created_at":"2024-11-12T02:01:25.639Z","updated_at":"2025-07-28T00:32:40.694Z","avatar_url":"https://github.com/Narazaka.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"# JSON::Schema::Serializer\n\n[![Actions Status](https://github.com/Narazaka/json-schema-serializer/workflows/Ruby/badge.svg)](https://github.com/Narazaka/json-schema-serializer/actions)\n[![Gem Version](https://badge.fury.io/rb/json-schema-serializer.svg)](https://badge.fury.io/rb/json-schema-serializer)\n\nJSON Schema based serializer\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem 'json-schema-serializer'\n```\n\nAnd then execute:\n\n    $ bundle\n\nOr install it yourself as:\n\n    $ gem install json-schema-serializer\n\n## Usage\n\n```ruby\nrequire \"json/schema/serializer\"\n\nschema = {\n  type: \"object\",\n  properties: {\n    id: { type: \"integer\" },\n    name: { type: \"string\" },\n    fuzzy: { type: [\"string\", \"integer\", \"null\"] },\n  },\n  required: [\"id\"],\n}\n\nserializer = JSON::Schema::Serializer.new(schema)\n\nserializer.serialize({id: \"42\", name: \"me\", foo: \"bar\", fuzzy: \"1000\"})\n# =\u003e {\"id\"=\u003e42, \"name\"=\u003e\"me\", \"fuzzy\"=\u003e\"1000\"}\n# \"42\" -\u003e 42! type coerced!\n\nserializer.serialize({id: \"42\", name: \"me\", fuzzy: 42})\n# =\u003e {\"id\"=\u003e42, \"name\"=\u003e\"me\", \"fuzzy\"=\u003e42}\nserializer.serialize({id: \"42\", name: \"me\"})\n# =\u003e {\"id\"=\u003e42, \"name\"=\u003e\"me\", \"fuzzy\"=\u003enil}\n# multiple type auto select!\n\nserializer.serialize({})\n# =\u003e {\"id\"=\u003e0, \"name\"=\u003enil, \"fuzzy\"=\u003enil}\n# nil -\u003e 0! required property's type coerced!\n\nserializer.serialize({id: 10, name: \"I don't need null keys!\"}).compact\n# =\u003e {\"id\"=\u003e10, \"name\"=\u003e\"I don't need null keys!\"}\n# compact it!\n\nclass A\n  def id\n    42\n  end\nend\nserializer.serialize(A.new)\n# =\u003e {\"id\"=\u003e42, \"name\"=\u003enil, \"fuzzy\"=\u003enil}\n# method also allowed\n\nclass Schema\n  def type\n    :string\n  end\nend\nserializer2 = JSON::Schema::Serializer.new(Schema.new)\nserializer2.serialize(32)\n# =\u003e \"32\"\n# non-hash schema allowed\n\n#\n# object injector allowed!\n#\n\nclass FooSerializer\n  def initialize(model)\n    @model = model\n  end\n\n  def first\n    @model.first\n  end\n\n  def count\n    @model.size\n  end\nend\n\nserializer_injected = JSON::Schema::Serializer.new(\n  {\n    type: :object,\n    inject: :Foo,\n    properties: {\n      first: { type: :integer },\n      count: { type: :integer },\n    },\n  },\n  {\n    inject_key: :inject,\n    injectors: {\n      Foo: FooSerializer,\n    },\n  },\n)\n\nserializer_injected.serialize([1, 2, 3])\n# =\u003e {\"first\"=\u003e1, \"count\"=\u003e3}\n\n#\n# object injector with context\n#\n\nclass BarSerializer\n  def initialize(model, context = nil)\n    @model = model\n    @context = context\n  end\n\n  def id\n    @model[:id]\n  end\n\n  def score\n    @context[@model[:id]]\n  end\nend\n\ninject_context = {\n  1 =\u003e 100,\n  2 =\u003e 200,\n}\n\nserializer_injected_with_context = JSON::Schema::Serializer.new(\n  {\n    type: :object,\n    inject: :Bar,\n    properties: {\n      id: { type: :integer },\n      score: { type: :integer },\n    },\n  },\n  {\n    inject_key: :inject,\n    injectors: {\n      Bar: BarSerializer,\n    },\n    inject_context: inject_context,\n  },\n)\n\nserializer_injected_with_context.serialize({ id: 1 })\n# =\u003e { \"id\" =\u003e 1, \"score\" =\u003e 100 }\n\n#\n# inject in serializer\n#\n\nclass ParentSerializer\n  include JSON::Schema::Serializer::WithContext\n\n  def initialize(model, context = nil)\n    @model = model\n    @context = context\n  end\n\n  def id\n    @model[:id]\n  end\n\n  def score\n    @context[:parent_scores][@model[:id]]\n  end\n\n  def child\n    # it can be\n    # with_context(context) { data }\n    # with_context(data, context)\n    # with_context(data: data, context: context)\n    with_context(@context.merge(child_scores: { 1 =\u003e 100, 2 =\u003e 200 })) do\n      @model[:child]\n    end\n  end\nend\n\nclass ChildSerializer\n  def initialize(model, context = nil)\n    @model = model\n    @context = context\n  end\n\n  def id\n    @model[:id]\n  end\n\n  def score\n    @context[:child_scores][@model[:id]]\n  end\nend\n\nserializer_injected_with_context_in_serializer = JSON::Schema::Serializer.new(\n  {\n    type: :object,\n    inject: :Parent,\n    properties: {\n      id: { type: :integer },\n      score: { type: :integer },\n      child: {\n        type: :object,\n        inject: :Child,\n        properties: {\n          id: { type: :integer },\n          score: { type: :integer },\n        },\n      },\n    },\n  },\n  {\n    inject_key: :inject,\n    injectors: {\n      Parent: ParentSerializer,\n      Child: ChildSerializer,\n    },\n    inject_context: { 1 =\u003e 10, 2 =\u003e 20 },\n  },\n)\n\nserializer_injected_with_context_in_serializer.serialize({ id: 1, child: { id: 2 } })\n# =\u003e { \"id\" =\u003e 1, \"score\" =\u003e 10, \"child\" =\u003e { \"id\" =\u003e 2, \"score\" =\u003e 200 } }\n\n#\n# also you can inject context with arraylike data\n#\n\nclass ItemsSerializer\n  include JSON::Schema::Serializer::WithContext\n\n  def initialize(models, context = nil)\n    @models = models\n    @context = context\n  end\n\n  def map(\u0026block)\n    context = (@context || {}).merge(scores: {...})\n    @models.map { |model| block.call(with_context(model, context)) }\n    # CAUTION!\n    # not like below!\n    # with_context(@models.map(\u0026block), context)\n    # with_context(context) { @models.map(\u0026block) }\n  end\nend\n\n#\n# inject model can initialize by keywords\n#\n\nclass KeywordSerializer\n  def initialize(data:, context: nil)\n    @data = data\n    @context = context\n  end\n\n  ...\nend\n\nserializer_with_keyword_init_inject = JSON::Schema::Serializer.new(\n  {\n    type: :object,\n    inject: :Keyword,\n    properties: { ... },\n  },\n  {\n    inject_key: :inject,\n    injectors: {\n      Keyword: KeywordSerializer,\n      Child: ChildSerializer,\n    },\n    inject_by_keyword: true, # \u003c- keyword_init!\n  },\n)\n```\n\n### \"additionalProperties\"\n\n\"additionalProperties\" is allowed but must be a schema object or `false`. (not `true`)\n\nIf \"additionalProperties\" does not exists, this serializer works as `{ additionalProperties\": false }`.\n\n### `$ref` resolving\n\n`JSON::Schema::Serializer` does not resolve `$ref` so use external resolver.\n\nwith `hana` and `json_refs` gem example:\n\n```ruby\nrequire \"hana\"\nrequire \"json_refs\"\nrequire \"json/schema/serializer\"\n\nschema = {\n  \"type\" =\u003e \"object\",\n  \"properties\" =\u003e {\n    \"foo\" =\u003e { \"type\" =\u003e \"integer\" },\n    \"bar\" =\u003e { \"$ref\" =\u003e \"#/properties/foo\" },\n  },\n}\n\nserializer = JSON::Schema::Serializer.new(JsonRefs.(schema))\nserializer.serialize({foo: 0, bar: \"42\"})\n# =\u003e {\"foo\"=\u003e0, \"bar\"=\u003e42}\n\n# resolver option also available\n\ndef walk(all, part)\n  if part.is_a?(Array)\n    part.map { |item| walk(all, item) }\n  elsif part.is_a?(Hash)\n    ref = part[\"$ref\"] || part[:\"$ref\"]\n    if ref\n      Hana::Pointer.new(ref[1..-1]).eval(all)\n    else\n      part.map { |k, v| [k, walk(all, v)] }.to_h\n    end\n  else\n    part\n  end\nend\n\nserializer2 = JSON::Schema::Serializer.new(schema[\"properties\"][\"bar\"], {\n  resolver: -\u003e(part_schema) do\n    walk(JsonRefs.(schema), part_schema))\n  end\n})\n```\n\n## JSON::Schema::Serializer API\n\n### .new(schema, options = nil)\n\nThe initializer.\n\n#### schema [any]\n\nJSON schema object. The serializer tries schema[\"type\"], schema[:type] and schema.type!\n\n#### options [Hash]\n\noptions\n\n#### options[:resolver] [Proc]\n\nschema object `$ref` resolver\n\n#### options[:schema_key_transform_for_input] [Proc]\n\ninput key transform\n\n```ruby\nnew({\n  type: :object,\n  properties: {\n    userCount: { type: :integer },\n  },\n}, { schema_key_transform_for_input: -\u003e(name) { name.underscore } }).serialize({ user_count: 1 }) == { \"userCount\" =\u003e 1 }\n```\n\n#### options[:schema_key_transform_for_output] [Proc]\n\noutput key transform\n\n```ruby\nnew({\n  type: :object,\n  properties: {\n    userCount: { type: :integer },\n  },\n}, { schema_key_transform_for_output: -\u003e(name) { name.underscore } }).serialize({ userCount: 1 }) == { \"user_count\" =\u003e 1 }\n```\n\n#### options[:injectors] [Hashlike\u003cString, Class\u003e, Class], options[:inject_key] [String, Symbol], options[:inject_context] [any], options[:inject_by_keyword] [Boolean]\n\nIf schema has inject key, the serializer treats data by `injectors[inject_key].new(data)` (or `injectors.send(inject_key).new(data)`).\n\nAnd if `inject_context` is present, `injectors[inject_key].new(data, inject_context)` (or `injectors.send(inject_key).new(data, inject_context)`).\n\nAnd if `inject_by_keyword` is true, `new(data, inject_context)` will be `new(data: data, context: inject_context)`.\n\nSee examples in [Usage](#usage).\n\nCAUTION: In many case you should define the `nil?` method in the injector class because Injector always initialized by `Injector.new(obj)` even if obj == nil.\n\n#### options[:null_through] [Boolean]\n\nIf data is null, always serialize null.\n\n```ruby\nnew({ type: :string }, { null_through: true }).serialize(nil) == nil\n```\n\n#### options[:empty_string_number_coerce_null] [Boolean]\n\nIf data == \"\" in integer or number schema, returns nil.\n\n```ruby\nnew({ type: :integer }, { empty_string_number_coerce_null: true }).serialize(\"\") == nil\n```\n\n#### options[:empty_string_boolean_coerce_null] [Boolean]\n\nIf data == \"\" in boolean schema, returns nil.\n\n```ruby\nnew({ type: :boolean }, { empty_string_boolean_coerce_null: true }).serialize(\"\") == nil\n```\n\n#### options[:false_values] [Enumerable]\n\nIf specified, boolean schema treats `!false_values.include?(data)`.\n\n```ruby\nnew({ type: :boolean }, { false_values: Set.new([false]) }).serialize(nil) == true\n```\n\n#### options[:no_boolean_coerce] [Boolean]\n\nIf true, boolean schema treats only `true` to be `true`.\n\n```ruby\nnew({ type: :boolean }, { no_boolean_coerce: true }).serialize(1) == false\n```\n\n#### options[:guard_primitive_in_structure] [Boolean]\n\nIf true, array or object schema does not accept primitive data and returns empty value.\n\n\n```ruby\nnew({ type: :object }, { guard_primitive_in_structure: true }).serialize(1) == {}\nnew({ type: :object }, { guard_primitive_in_structure: true, null_through: true }).serialize(1) == nil\n```\n\n### #serialize(data)\n\nSerialize the object data by the schema.\n\n#### data [any]\n\nSerialize target object. The serializer tries data[\"foo\"], data[:foo] and data.foo!\n\n## JSON::Schema::Serializer::WithContext API\n\n### #with_context!(data, context), #with_context!(data: data, context: context), #with_context!(context) { data }\n\nIf you use `with_context!(data, context)` as the return value of the serializer, then \"child\" serializer can use that context.\n\nSee examples in [Usage](#usage).\n\n## License\n\nZlib License\n\n## Development\n\nAfter checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.\n\nTo install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at https://github.com/Narazaka/json-schema-serializer.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnarazaka%2Fjson-schema-serializer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnarazaka%2Fjson-schema-serializer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnarazaka%2Fjson-schema-serializer/lists"}