Skip to content

InvalidSymbolKey error when using symbol keys in schema #72

@stanig2106

Description

@stanig2106

Hello,

I'm currently using the activerecord_json_validator gem in a project and I've come across an issue when I use symbol keys in the JSON schema. Here's the code where the issue arises:

validates :data, json: {
  schema: {
    type: :object,
    properties: {
      time: { type: :number, minimum: 0 }
    },
    required: %i[time]
  }
}

When I run this, I get the following error:

JSONSchemer::InvalidSymbolKey: schemas must use string keys

This error seems to be raised from the JSONSchemer::Schema::Base#initialize method when the schema is a Hash, is not empty, and the first key in the schema is not a string. Here's the code block where this happens:

raise InvalidSymbolKey, 'schemas must use string keys' if schema.is_a?(Hash) && !schema.empty? && !schema.first.first.is_a?(String)

Proposed Solution:

As a simple fix for this issue, instead of raising an error when the schema contains symbol keys, the schema could be modified to convert all keys to strings. We can use Hash#deep_stringify_keys (from active_support) method on the schema.

This change would make the gem more flexible and user-friendly by eliminating the need for users to ensure that their schemas only use string keys. I believe this would be a beneficial change and would appreciate if it could be considered for implementation.

Thank you for your time and consideration.

Best,
Stani

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions