Oj::Safe

oj-safe is a safe JSON parser built on top of Oj.

Oj::Safe lets you parse JSON while enforcing configurable limits on the input size and structure, helping protect applications from excessively large or deeply nested payloads.

Installation

Add this to your Gemfile:

gem "oj-safe"

Or install it directly:

gem install oj-safe

Available configuration options

max_hash_size

Maximum number of key/value pairs allowed in a JSON object.

parser = Oj::Safe.new(max_hash_size: 2)

parser.parse('{ "foo": 1, "bar": 2 }') # => { "foo" => 1, "bar" => 2 }
parser.parse('{ "foo": 1, "bar": 2, "baz": 3 }') # => Raises `Oj::Safe::HashSizeError`.
max_array_size

Maximum number of items allowed in a JSON array.

parser = Oj::Safe.new(max_array_size: 2)

parser.parse('[1, 2]') # => [1, 2]
parser.parse('[1, 2, 3]') # => Raises `Oj::Safe::ArraySizeError`.
max_depth

Maximum nesting depth allowed.

parser = Oj::Safe.new(max_depth: 2)

parser.parse('[[]]') # => [[]]
parser.parse('[[[]]]]') # => Raises `Oj::Safe::DepthError`.
max_total_elements

Maximum total number of parsed elements.

parser = Oj::Safe.new(max_total_elements: 2)

parser.parse('[true]') # => [true]
parser.parse('[true, false]') # => Raises `Oj::Safe::TotalElementsError`.
max_json_size_bytes

Maximum size of the input JSON string in bytes.

parser = Oj::Safe.new(max_json_size_bytes: 2)

parser.parse('12') # => 12
parser.parse('123') # => Raises `Oj::Safe::PayloadSizeError`.

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake to compile and run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To 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 the created tag, and push the .gem file to rubygems.org.

Contributing

Bug reports and merge requests are welcome on GitLab at https://gitlab.com/minac/oj-safe. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Oj::Safe project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.