Oj Ruby Documentation

repository·develop·Indexed 25 days ago

https://github.com/ohler55/oj

A high-performance JSON parser and Object marshaller for Ruby. Oj provides various modes for compatibility with strict JSON, the standard Ruby JSON gem, and Rails/ActiveSupport. It features a C extension for speed, SIMD optimizations, and multiple parsing APIs including Oj::Doc for fast navigation, as well as callback-based parsing via Oj::Saj and Oj::ScHandler.

Tokens
14.9K
Snippets
20
Records
59
Agent score
84%

What's inside Oj

  1. Understand Oj Modes

    develop

    Oj uses different modes to control how JSON is loaded and dumped. The mode determines the expected input format and the resulting output structure. It is highly recommended to use the same mode for both loading and dumping to avoid unexpected behavior.

    Available modes include:

    • :strict
    • :null
    • :compat (or :json)
    • :rails
    • :object
    • :custom
    • :wab (specifically for the WABuR project)
  2. Use Oj::Parser for high-performance JSON parsing

    develop

    The Oj::Parser is a high-performance alternative to the legacy Oj.load parser. Unlike the global Oj.load approach, Oj::Parser uses isolated parser instances, meaning options set on one parser do not leak into others. This makes it ideal for applications that need to handle different JSON formats or compatibility requirements (e.g., switching between Rails-style and JSON gem-style parsing) within the same process.

    Key benefits include:

    • Performance: Up to 3x faster than the previous parser in some modes.
    • Isolation: Each parser instance maintains its own configuration and state.
    • Re-entrancy: The parser is re-entrant, allowing partial blocks of JSON to be parsed and results to be combined.
    • Efficiency: Uses character maps and reduced conditional branching to minimize overhead.
  3. SIMD optimizations in Oj

    develop

    Oj enables SIMD optimizations automatically at runtime. It detects available CPU features and selects the optimal implementation without requiring any specific installation flags. Supported optimizations include:

    • x86 / x86_64: SSE4.2 or SSE2
    • ARM: NEON
    • Fallback: Scalar implementation if no SIMD features are detected.

    Note: The --with-sse42 install option used in earlier versions has been removed; SSE4.2 is now selected automatically.

  4. Handle empty or whitespace input with :empty_string

    develop

    By default, parsing an empty or whitespace-only string raises an exception. If you want to allow this, set :empty_string to true.

    Note the behavior differences compared to the standard JSON gem:

    • JSON.parse('') raises an error.
    • Oj.load('', empty_string: true) returns nil.

    This option is honored for :null, :strict, and :custom modes, but is ignored for :custom and :wab modes. For :compat mode, the rules are more complex.

  5. Use Oj :custom mode for maximum configuration

    develop
    The :custom mode is the most flexible mode in Oj, honoring almost all options. While it cannot be configured to behave exactly like the :object or :compat modes (which have unique internal behaviors for object dumping and JSON gem mimicry), it provides the highest level of configurability. You can use :custom mode by passing options directly to Oj.dump() and Oj.load() or by modifying the global default options.
  6. Configure the 'usual' delegate for Ruby object creation

    develop

    The usual delegate is designed to build Ruby objects efficiently. It includes several optimization features that can be configured via method calls on the parser instance:

    • Symbol Keys: Use option methods to toggle :symbol_keys. The parser optimizes this by changing function pointers at configuration time rather than checking the option during every parse step.
    • Caching: You can enable or disable caching for Ruby objects (Strings, Arrays, or specific classes). This reduces the cost of resolving class names and creating repetitive objects like Hash keys. You can also specify a larger initial cache size to reduce the frequency of rehashes.
    • Object Creation Strategy: By default, the parser can be configured to follow the JSON gem's approach of creating a Hash and then calling #json_create(arg). However, for better performance, you can use an approach that creates the Object directly and sets attributes without ever creating the intermediate Hash.
  7. Use WAB mode for data exchange

    develop

    The :wab mode is a specialized encoding mode designed to support the WABuR project. It is optimized for performance, performing slightly faster than :strict and :null modes.

    In this mode, only the indent option is supported. All other options are ignored to ensure that the encoding and formats remain consistent with the WAB system API, preventing data exchange breakage between components.

    When using :wab mode, encoding behaves like :strict mode, but with explicit support for the following types: URI, Time, WAB::UUID, and BigDecimal.

  8. Configure Oj Rails Compatibility Mode

    develop

    Oj provides a :rails mode that mimics the ActiveSupport version 5 encoder. This mode respects the as_json(*) method used by Rails/ActiveSupport.

    You can set up Rails compatibility using Oj.optimize_rails() or by calling the specific configuration methods:

    require 'oj'
    
    Oj::Rails.set_encoder()
    Oj::Rails.set_decoder()
    Oj::Rails.optimize()
    Oj::Rails.mimic_JSON()

    Note on Default Mode: These steps set up Oj to mimic Rails, but they do not change the default Oj mode type. If you want :rails to be the default mode for all direct Oj calls, you must set it via Oj.default_options.

  9. Make Oj mimic the JSON gem

    develop

    To have Oj universally replace methods on the JSON constant (such as load, parse, etc.) with faster Oj counterparts in a mode compatible with the json gem, call Oj.mimic_JSON().

    If your project already requires the json gem, ensure Oj.mimic_JSON() is invoked after the json gem has been required.

    Oj.mimic_JSON()