module Oj

Optimized JSON (Oj), as the name implies was written to provide speed optimized JSON handling.

Oj has several dump or serialization modes which control how Objects are converted to JSON. These modes are set with the :mode option in either the default options or as one of the options to the dump() method.

Constants

VERSION

Current version of the module.

Public Class Methods

compat_load(json, options) → Object, Hash, Array, String, Fixnum, Float, true, false, or nil

Parses a JSON document String into an Object, Hash, Array, String, Fixnum, Float, true, false, or nil. It parses using a mode that is generally compatible with other Ruby JSON parsers in that it will create objects based on the :create_id value. It is not compatible in every way to every other parser though as each parser has it's own variations.

When used with a document that has multiple JSON elements the block, if any, will be yielded to. If no block then the last element read will be returned.

Raises an exception if the JSON is malformed or the classes specified are not valid. If the input is not a valid JSON document (an empty string is not a valid JSON document) an exception is raised.

A block can also be provided with a single argument. That argument will be the parsed JSON document. This is useful when parsing a string that includes multiple JSON documents.

@param [String|IO] json JSON String or an Object that responds to read() @param [Hash] options load options (same as ::default_options)

default_options() → Hash click to toggle source

Returns the default load and dump options as a Hash. The options are

  • indent: [Fixnum|String|nil] number of spaces to indent each element in an JSON document, zero or nil is no newline between JSON elements, negative indicates no newline between top level JSON elements in a stream, a String indicates the string should be used for indentation

  • circular: [true|false|nil] support circular references while dumping

  • auto_define: [true|false|nil] automatically define classes if they do not exist

  • symbol_keys: [true|false|nil] use symbols instead of strings for hash keys

  • escape_mode: [:newline|:json|:xss_safe|:ascii|nil] determines the characters to escape

  • class_cache: [true|false|nil] cache classes for faster parsing (if dynamically modifying classes or reloading classes then don't use this)

  • mode: [:object|:strict|:compat|:null] load and dump modes to use for JSON

  • time_format: [:unix|:unix_zone|:xmlschema|:ruby] time format when dumping in :compat and :object mode

  • bigdecimal_as_decimal: [true|false|nil] dump BigDecimal as a decimal number or as a String

  • bigdecimal_load: [:bigdecimal|:float|:auto] load decimals as BigDecimal instead of as a Float. :auto pick the most precise for the number of digits.

  • create_id: [String|nil] create id for json compatible object encoding, default is 'json_create'

  • second_precision: [Fixnum|nil] number of digits after the decimal when dumping the seconds portion of time

  • float_precision: [Fixnum|nil] number of digits of precision when dumping floats, 0 indicates use Ruby

  • use_to_json: [true|false|nil] call to_json() methods on dump, default is false

  • use_as_json: [true|false|nil] call #as_json() methods on dump, default is false

  • nilnil: [true|false|nil] if true a nil input to load will return nil and not raise an Exception

  • allow_gc: [true|false|nil] allow or prohibit GC during parsing, default is true (allow)

  • quirks_mode: [true,|false|nil] Allow single JSON values instead of documents, default is true (allow)

  • allow_invalid_unicode: [true,|false|nil] Allow invalid unicode, default is false (don't allow)

  • indent_str: [String|nil] String to use for indentation, overriding the indent option is not nil

  • space: [String|nil] String to use for the space after the colon in JSON object fields

  • space_before: [String|nil] String to use before the colon separator in JSON object fields

  • object_nl: [String|nil] String to use after a JSON object field value

  • array_nl: [String|nil] String to use after a JSON array value

  • nan: [:null|:huge|:word|:raise|:auto] how to dump Infinity and NaN in null, strict, and compat mode. :null places a null, :huge places a huge number, :word places Infinity or NaN, :raise raises and exception, :auto uses default for each mode.

  • hash_class: [Class|nil] Class to use instead of Hash on load

  • omit_nil: [true|false] if true Hash and Object attributes with nil values are omitted

@return [Hash] all current option settings.

static VALUE
get_def_opts(VALUE self) {
    VALUE       opts = rb_hash_new();

    if (0 == oj_default_options.dump_opts.indent_size) {
        rb_hash_aset(opts, indent_sym, INT2FIX(oj_default_options.indent));
    } else {
        rb_hash_aset(opts, indent_sym, rb_str_new2(oj_default_options.dump_opts.indent_str));
    }
    rb_hash_aset(opts, sec_prec_sym, INT2FIX(oj_default_options.sec_prec));
    rb_hash_aset(opts, circular_sym, (Yes == oj_default_options.circular) ? Qtrue : ((No == oj_default_options.circular) ? Qfalse : Qnil));
    rb_hash_aset(opts, class_cache_sym, (Yes == oj_default_options.class_cache) ? Qtrue : ((No == oj_default_options.class_cache) ? Qfalse : Qnil));
    rb_hash_aset(opts, auto_define_sym, (Yes == oj_default_options.auto_define) ? Qtrue : ((No == oj_default_options.auto_define) ? Qfalse : Qnil));
    rb_hash_aset(opts, symbol_keys_sym, (Yes == oj_default_options.sym_key) ? Qtrue : ((No == oj_default_options.sym_key) ? Qfalse : Qnil));
    rb_hash_aset(opts, bigdecimal_as_decimal_sym, (Yes == oj_default_options.bigdec_as_num) ? Qtrue : ((No == oj_default_options.bigdec_as_num) ? Qfalse : Qnil));
    rb_hash_aset(opts, use_to_json_sym, (Yes == oj_default_options.to_json) ? Qtrue : ((No == oj_default_options.to_json) ? Qfalse : Qnil));
    rb_hash_aset(opts, use_as_json_sym, (Yes == oj_default_options.as_json) ? Qtrue : ((No == oj_default_options.as_json) ? Qfalse : Qnil));
    rb_hash_aset(opts, nilnil_sym, (Yes == oj_default_options.nilnil) ? Qtrue : ((No == oj_default_options.nilnil) ? Qfalse : Qnil));
    rb_hash_aset(opts, allow_gc_sym, (Yes == oj_default_options.allow_gc) ? Qtrue : ((No == oj_default_options.allow_gc) ? Qfalse : Qnil));
    rb_hash_aset(opts, quirks_mode_sym, (Yes == oj_default_options.quirks_mode) ? Qtrue : ((No == oj_default_options.quirks_mode) ? Qfalse : Qnil));
    rb_hash_aset(opts, allow_invalid_unicode_sym, (Yes == oj_default_options.allow_invalid) ? Qtrue : ((No == oj_default_options.allow_invalid) ? Qfalse : Qnil));
    rb_hash_aset(opts, float_prec_sym, INT2FIX(oj_default_options.float_prec));
    switch (oj_default_options.mode) {
    case StrictMode:    rb_hash_aset(opts, mode_sym, strict_sym);  break;
    case CompatMode:    rb_hash_aset(opts, mode_sym, compat_sym);  break;
    case NullMode:      rb_hash_aset(opts, mode_sym, null_sym);              break;
    case ObjectMode:
    default:            rb_hash_aset(opts, mode_sym, object_sym); break;
    }
    switch (oj_default_options.escape_mode) {
    case NLEsc:         rb_hash_aset(opts, escape_mode_sym, newline_sym);      break;
    case JSONEsc:       rb_hash_aset(opts, escape_mode_sym, json_sym);                break;
    case XSSEsc:        rb_hash_aset(opts, escape_mode_sym, xss_safe_sym);     break;
    case ASCIIEsc:      rb_hash_aset(opts, escape_mode_sym, ascii_sym);              break;
    default:            rb_hash_aset(opts, escape_mode_sym, json_sym);            break;
    }
    switch (oj_default_options.time_format) {
    case XmlTime:       rb_hash_aset(opts, time_format_sym, xmlschema_sym);   break;
    case RubyTime:      rb_hash_aset(opts, time_format_sym, ruby_sym);               break;
    case UnixZTime:     rb_hash_aset(opts, time_format_sym, unix_zone_sym); break;
    case UnixTime:
    default:            rb_hash_aset(opts, time_format_sym, unix_sym);            break;
    }
    switch (oj_default_options.bigdec_load) {
    case BigDec:        rb_hash_aset(opts, bigdecimal_load_sym, bigdecimal_sym);break;
    case FloatDec:      rb_hash_aset(opts, bigdecimal_load_sym, float_sym);  break;
    case AutoDec:
    default:            rb_hash_aset(opts, bigdecimal_load_sym, auto_sym);        break;
    }
    rb_hash_aset(opts, create_id_sym, (0 == oj_default_options.create_id) ? Qnil : rb_str_new2(oj_default_options.create_id));
    rb_hash_aset(opts, space_sym, (0 == oj_default_options.dump_opts.after_size) ? Qnil : rb_str_new2(oj_default_options.dump_opts.after_sep));
    rb_hash_aset(opts, space_before_sym, (0 == oj_default_options.dump_opts.before_size) ? Qnil : rb_str_new2(oj_default_options.dump_opts.before_sep));
    rb_hash_aset(opts, object_nl_sym, (0 == oj_default_options.dump_opts.hash_size) ? Qnil : rb_str_new2(oj_default_options.dump_opts.hash_nl));
    rb_hash_aset(opts, array_nl_sym, (0 == oj_default_options.dump_opts.array_size) ? Qnil : rb_str_new2(oj_default_options.dump_opts.array_nl));

    switch (oj_default_options.dump_opts.nan_dump) {
    case NullNan:       rb_hash_aset(opts, nan_sym, null_sym);        break;
    case RaiseNan:      rb_hash_aset(opts, nan_sym, raise_sym);      break;
    case WordNan:       rb_hash_aset(opts, nan_sym, word_sym);        break;
    case HugeNan:       rb_hash_aset(opts, nan_sym, huge_sym);        break;
    case AutoNan:
    default:            rb_hash_aset(opts, nan_sym, auto_sym);    break;
    }
    rb_hash_aset(opts, omit_nil_sym, oj_default_options.dump_opts.omit_nil ? Qtrue : Qfalse);
    rb_hash_aset(opts, hash_class_sym, oj_default_options.hash_class);
    
    return opts;
}
default_options=(opts) click to toggle source

Sets the default options for load and dump. @param [Hash] opts options to change @param [Fixnum|String|nil] :indent number of spaces to indent each element in a JSON document or the String to use for identation. @param [true|false|nil] :circular support circular references while dumping @param [true|false|nil] :auto_define automatically define classes if they do not exist @param [true|false|nil] :symbol_keys convert hash keys to symbols @param [true|false|nil] :class_cache cache classes for faster parsing @param [:newline|:json|:xss_safe|:ascii|nil] :escape mode encodes all high-bit characters as

escaped sequences if :ascii, :json is standand UTF-8 JSON encoding,
:newline is the same as :json but newlines are not escaped,
and :xss_safe escapes &, <, and >, and some others.

@param [true|false|nil] :bigdecimal_as_decimal dump BigDecimal as a decimal number or as a String @param [:bigdecimal|:float|:auto|nil] :bigdecimal_load load decimals as BigDecimal instead of as a Float. :auto pick the most precise for the number of digits. @param [:object|:strict|:compat|:null] load and dump mode to use for JSON

:strict raises an exception when a non-supported Object is
encountered. :compat attempts to extract variable values from an
Object using to_json() or to_hash() then it walks the Object's
variables if neither is found. The :object mode ignores to_hash()
and to_json() methods and encodes variables using code internal to
the Oj gem. The :null mode ignores non-supported Objects and
replaces them with a null.

@param [:unix|:xmlschema|:ruby] time format when dumping in :compat mode

:unix decimal number denoting the number of seconds since 1/1/1970,
:unix_zone decimal number denoting the number of seconds since 1/1/1970 plus the utc_offset in the exponent ,
:xmlschema date-time format taken from XML Schema as a String,
:ruby Time.to_s formatted String

@param [String|nil] :create_id create id for json compatible object encoding @param [Fixnum|nil] :second_precision number of digits after the decimal when dumping the seconds portion of time @param [Fixnum|nil] :float_precision number of digits of precision when dumping floats, 0 indicates use Ruby @param [true|false|nil] :use_to_json call to_json() methods on dump, default is false @param [true|false|nil] :use_as_json call #as_json() methods on dump, default is false @param [true|false|nil] :nilnil if true a nil input to load will return nil and not raise an Exception @param [true|false|nil] :allow_gc allow or prohibit GC during parsing, default is true (allow) @param [true|false|nil] :quirks_mode allow single JSON values instead of documents, default is true (allow) @param [true|false|nil] :allow_invalid_unicode allow invalid unicode, default is false (don't allow) @param [String|nil] :space String to use for the space after the colon in JSON object fields @param [String|nil] :space_before String to use before the colon separator in JSON object fields @param [String|nil] :object_nl String to use after a JSON object field value @param [String|nil] :array_nl String to use after a JSON array value @param [:null|:huge|:word|:raise] :nan how to dump Infinity and NaN in null, strict, and compat mode. :null places a null, :huge places a huge number, :word places Infinity or NaN, :raise raises and exception, :auto uses default for each mode. @param [Class|nil] :hash_class Class to use instead of Hash on load @param [true|false] :omit_nil if true Hash and Object attributes with nil values are omitted @return [nil]

static VALUE
set_def_opts(VALUE self, VALUE opts) {
    Check_Type(opts, T_HASH);
    oj_parse_options(opts, &oj_default_options);

    return Qnil;
}
dump(obj, anIO=nil, limit = nil) → String click to toggle source

Encodes an object as a JSON String.

@param [Object] obj object to convert to encode as JSON @param [IO] anIO an IO that allows writing @param [Fixnum] limit ignored

static VALUE
dump(int argc, VALUE *argv, VALUE self) {
    char                buf[4096];
    struct _Out         out;
    struct _Options     copts = oj_default_options;
    VALUE               rstr;

    if (1 > argc) {
        rb_raise(rb_eArgError, "wrong number of arguments (0 for 1).");
    }
    if (2 == argc) {
        oj_parse_options(argv[1], &copts);
    }
    out.buf = buf;
    out.end = buf + sizeof(buf) - 10;
    out.allocated = 0;
    out.omit_nil = copts.dump_opts.omit_nil;
    oj_dump_obj_to_json(*argv, &copts, &out);
    if (0 == out.buf) {
        rb_raise(rb_eNoMemError, "Not enough memory.");
    }
    rstr = rb_str_new2(out.buf);
    rstr = oj_encode(rstr);
    if (out.allocated) {
        xfree(out.buf);
    }
    return rstr;
}
dump_default_options() click to toggle source
# File lib/oj/mimic.rb, line 148
def self.dump_default_options
  Oj::MimicDumpOption.new
end
dump_default_options=(h) click to toggle source
# File lib/oj/mimic.rb, line 152
def self.dump_default_options=(h)
  m = Oj::MimicDumpOption.new
  h.each do |k,v|
    m[k] = v
  end
end
json_create(h) click to toggle source
# File lib/oj/mimic.rb, line 56
def self.json_create(h)
  new(h['t'])
end
load(source, proc=nil) → Object click to toggle source

Loads a Ruby Object from a JSON source that can be either a String or an IO. If Proc is given or a block is providedit is called with each nested element of the loaded Object.

@param [String|IO] source JSON source @param [Proc] proc to yield to on each element or nil

static VALUE
load(int argc, VALUE *argv, VALUE self) {
    Mode        mode = oj_default_options.mode;

    if (1 > argc) {
        rb_raise(rb_eArgError, "Wrong number of arguments to load().");
    }
    if (2 <= argc) {
        VALUE  ropts = argv[1];
        VALUE  v;

        Check_Type(ropts, T_HASH);
        if (Qnil != (v = rb_hash_lookup(ropts, mode_sym))) {
            if (object_sym == v) {
                mode = ObjectMode;
            } else if (strict_sym == v) {
                mode = StrictMode;
            } else if (compat_sym == v) {
                mode = CompatMode;
            } else if (null_sym == v) {
                mode = NullMode;
            } else {
                rb_raise(rb_eArgError, ":mode must be :object, :strict, :compat, or :null.");
            }
        }
    }
    switch (mode) {
    case StrictMode:
        return oj_strict_parse(argc, argv, self);
    case NullMode:
    case CompatMode:
        return oj_compat_parse(argc, argv, self);
    case ObjectMode:
    default:
        break;
    }
    return oj_object_parse(argc, argv, self);
}
load_file(path, options) → Object, Hash, Array, String, Fixnum, Float, true, false, or nil click to toggle source

Parses a JSON document String into a Object, Hash, Array, String, Fixnum, Float, true, false, or nil according to the default mode or the mode specified. Raises an exception if the JSON is malformed or the classes specified are not valid. If the string input is not a valid JSON document (an empty string is not a valid JSON document) an exception is raised.

When used with a document that has multiple JSON elements the block, if any, will be yielded to. If no block then the last element read will be returned.

If the input file is not a valid JSON document (an empty file is not a valid JSON document) an exception is raised.

This is a stream based parser which allows a large or huge file to be loaded without pulling the whole file into memory.

A block can also be provided with a single argument. That argument will be the parsed JSON document. This is useful when parsing a string that includes multiple JSON documents.

@param [String] path path to a file containing a JSON document @param [Hash] options load options (same as ::default_options)

static VALUE
load_file(int argc, VALUE *argv, VALUE self) {
    char                *path;
    int                 fd;
    Mode                mode = oj_default_options.mode;
    struct _ParseInfo   pi;

    if (1 > argc) {
        rb_raise(rb_eArgError, "Wrong number of arguments to load().");
    }
    Check_Type(*argv, T_STRING);
    pi.options = oj_default_options;
    pi.handler = Qnil;
    pi.err_class = Qnil;
    if (2 <= argc) {
        VALUE  ropts = argv[1];
        VALUE  v;

        Check_Type(ropts, T_HASH);
        if (Qnil != (v = rb_hash_lookup(ropts, mode_sym))) {
            if (object_sym == v) {
                mode = ObjectMode;
            } else if (strict_sym == v) {
                mode = StrictMode;
            } else if (compat_sym == v) {
                mode = CompatMode;
            } else if (null_sym == v) {
                mode = NullMode;
            } else {
                rb_raise(rb_eArgError, ":mode must be :object, :strict, :compat, or :null.");
            }
        }
    }
    path = StringValuePtr(*argv);
    if (0 == (fd = open(path, O_RDONLY))) {
        rb_raise(rb_eIOError, "%s", strerror(errno));
    }
    switch (mode) {
    case StrictMode:
        oj_set_strict_callbacks(&pi);
        return oj_pi_sparse(argc, argv, &pi, fd);
    case NullMode:
    case CompatMode:
        oj_set_compat_callbacks(&pi);
        return oj_pi_sparse(argc, argv, &pi, fd);
    case ObjectMode:
    default:
        break;
    }
    oj_set_object_callbacks(&pi);

    return oj_pi_sparse(argc, argv, &pi, fd);
}
mimic_JSON() → Module click to toggle source

Creates the JSON module with methods and classes to mimic the JSON gem. After this method is invoked calls that expect the JSON module will use Oj instead and be faster than the original JSON. Most options that could be passed to the JSON methods are supported. The calls to set parser or generator will not raise an Exception but will not have any effect. The method can also be called after the json gem is loaded. The necessary methods on the json gem will be replaced with Oj methods.

Note that this also sets the default options of :mode to :compat and :encoding to :ascii.

static VALUE
define_mimic_json(int argc, VALUE *argv, VALUE self) {
    VALUE       ext;
    VALUE       dummy;
    VALUE       verbose;
    VALUE       json_error;
    
    // Either set the paths to indicate JSON has been loaded or replaces the
    // methods if it has been loaded.
    if (rb_const_defined_at(rb_cObject, rb_intern("JSON"))) {
        mimic = rb_const_get_at(rb_cObject, rb_intern("JSON"));
    } else {
        mimic = rb_define_module("JSON");
    }
    verbose = rb_gv_get("$VERBOSE");
    rb_gv_set("$VERBOSE", Qfalse);
    rb_define_module_function(rb_cObject, "JSON", mimic_dump_load, -1);
    if (rb_const_defined_at(mimic, rb_intern("Ext"))) {
        ext = rb_const_get_at(mimic, rb_intern("Ext"));
     } else {
        ext = rb_define_module_under(mimic, "Ext");
    }
    if (!rb_const_defined_at(ext, rb_intern("Parser"))) {
        dummy = rb_define_class_under(ext, "Parser", rb_cObject);
    }
    if (!rb_const_defined_at(ext, rb_intern("Generator"))) {
        dummy = rb_define_class_under(ext, "Generator", rb_cObject);
    }
    // convince Ruby that the json gem has already been loaded
    dummy = rb_gv_get("$LOADED_FEATURES");
    if (rb_type(dummy) == T_ARRAY) {
        rb_ary_push(dummy, rb_str_new2("json"));
        if (0 < argc) {
            VALUE      mimic_args[1];

            *mimic_args = *argv;
            rb_funcall2(Oj, rb_intern("mimic_loaded"), 1, mimic_args);
        } else {
            rb_funcall2(Oj, rb_intern("mimic_loaded"), 0, 0);
        }
    }
    rb_define_module_function(mimic, "parser=", no_op1, 1);
    rb_define_module_function(mimic, "generator=", no_op1, 1);
    rb_define_module_function(mimic, "create_id=", mimic_set_create_id, 1);
    rb_define_module_function(mimic, "create_id", mimic_create_id, 0);

    rb_define_module_function(mimic, "dump", mimic_dump, -1);
    rb_define_module_function(mimic, "load", mimic_load, -1);
    rb_define_module_function(mimic, "restore", mimic_load, -1);
    rb_define_module_function(mimic, "recurse_proc", mimic_recurse_proc, 1);
    rb_define_module_function(mimic, "[]", mimic_dump_load, -1);

    rb_define_module_function(mimic, "generate", mimic_generate, -1);
    rb_define_module_function(mimic, "fast_generate", mimic_generate, -1);
    rb_define_module_function(mimic, "pretty_generate", mimic_pretty_generate, -1);
    /* for older versions of JSON, the deprecated unparse methods */
    rb_define_module_function(mimic, "unparse", mimic_generate, -1);
    rb_define_module_function(mimic, "fast_unparse", mimic_generate, -1);
    rb_define_module_function(mimic, "pretty_unparse", mimic_pretty_generate, -1);

    rb_define_module_function(mimic, "parse", mimic_parse, -1);
    rb_define_module_function(mimic, "parse!", mimic_parse, -1);

    rb_define_method(rb_cObject, "to_json", mimic_object_to_json, -1);

    rb_gv_set("$VERBOSE", verbose);

    create_additions_sym = ID2SYM(rb_intern("create_additions"));       rb_gc_register_address(&create_additions_sym);
    symbolize_names_sym = ID2SYM(rb_intern("symbolize_names"));         rb_gc_register_address(&symbolize_names_sym);

    if (rb_const_defined_at(mimic, rb_intern("JSONError"))) {
        json_error = rb_const_get(mimic, rb_intern("JSONError"));
    } else {
        json_error = rb_define_class_under(mimic, "JSONError", rb_eStandardError);
    }
    if (rb_const_defined_at(mimic, rb_intern("ParserError"))) {
        json_parser_error_class = rb_const_get(mimic, rb_intern("ParserError"));
    } else {
        json_parser_error_class = rb_define_class_under(mimic, "ParserError", json_error);
    }

    if (!rb_const_defined_at(mimic, rb_intern("State"))) {
        rb_define_class_under(mimic, "State", rb_cObject);
    }

    oj_default_options = mimic_object_to_json_options;
    oj_default_options.to_json = Yes;

    return mimic;
}
mimic_loaded(mimic_paths=[]) click to toggle source
# File lib/oj/mimic.rb, line 32
def self.mimic_loaded(mimic_paths=[])
  $LOAD_PATH.each do |d|
    next unless File.exist?(d)

    jfile = File.join(d, 'json.rb')
    $LOADED_FEATURES << jfile unless $LOADED_FEATURES.include?(jfile) if File.exist?(jfile)
    
    Dir.glob(File.join(d, 'json', '**', '*.rb')).each do |file|
      $LOADED_FEATURES << file unless $LOADED_FEATURES.include?(file)
    end
  end
  mimic_paths.each { |p| $LOADED_FEATURES << p }
  $LOADED_FEATURES << 'json' unless $LOADED_FEATURES.include?('json')

  if Object.const_defined?('OpenStruct')
    OpenStruct.class_eval do
      # Both the JSON gem and Rails monkey patch as_json. Let them battle it out.
      unless defined?(self.as_json)
        def as_json(*)
          name = self.class.name.to_s
          raise JSON::JSONError, "Only named structs are supported!" if 0 == name.length
          { JSON.create_id => name, 't' => table }
        end
      end
      def self.json_create(h)
        new(h['t'])
      end
    end
  end

  Range.class_eval do
    # Both the JSON gem and Rails monkey patch as_json. Let them battle it out.
    unless defined?(self.as_json)
      def as_json(*)
        {JSON.create_id => 'Range', 'a' => [first, last, exclude_end?]}
      end
    end
    def self.json_create(h)
      new(h['a'])
    end
  end

  Rational.class_eval do
    # Both the JSON gem and Rails monkey patch as_json. Let them battle it out.
    unless defined?(self.as_json)
      def as_json(*)
        {JSON.create_id => 'Rational', 'n' => numerator, 'd' => denominator }
      end
    end
    def self.json_create(h)
      Rational(h['n'], h['d'])
    end
  end

  Regexp.class_eval do
    # Both the JSON gem and Rails monkey patch as_json. Let them battle it out.
    unless defined?(self.as_json)
      def as_json(*)
        {JSON.create_id => 'Regexp', 'o' => options, 's' => source }
      end
    end
    def self.json_create(h)
      new(h['s'], h['o'])
    end
  end

  Struct.class_eval do
    # Both the JSON gem and Rails monkey patch as_json. Let them battle it out.
    unless defined?(self.as_json)
      def as_json(*)
        name = self.class.name.to_s
        raise JSON::JSONError, "Only named structs are supported!" if 0 == name.length
        { JSON.create_id => name, 'v' => values }
      end
    end
    def self.json_create(h)
      new(h['v'])
    end
  end

  Symbol.class_eval do
    # Both the JSON gem and Rails monkey patch as_json. Let them battle it out.
    unless defined?(self.as_json)
      def as_json(*)
        {JSON.create_id => 'Symbol', 's' => to_s }
      end
    end
    def self.json_create(h)
      h['s'].to_sym
    end
  end

  Time.class_eval do
    # Both the JSON gem and Rails monkey patch as_json. Let them battle it out.
    unless defined?(self.as_json)
      def as_json(*)
        {JSON.create_id => 'Symbol', 's' => to_s }
        nsecs = [ tv_usec * 1000 ]
        nsecs << tv_nsec if respond_to?(:tv_nsec)
        nsecs = nsecs.max
        { JSON.create_id => 'Time', 's' => tv_sec, 'n' => nsecs }
      end
    end
    def self.json_create(h)
      if usec = h.delete('u')
        h['n'] = usec * 1000
      end
      if instance_methods.include?(:tv_nsec)
        at(h['s'], Rational(h['n'], 1000))
      else
        at(h['s'], h['n'] / 1000)
      end
    end
  end

  JSON.module_eval do
    def self.dump_default_options
      Oj::MimicDumpOption.new
    end

    def self.dump_default_options=(h)
      m = Oj::MimicDumpOption.new
      h.each do |k,v|
        m[k] = v
      end
    end
  end

end
object_load(json, options) → Object, Hash, Array, String, Fixnum, Float, true, false, or nil

Parses a JSON document String into an Object, Hash, Array, String, Fixnum, Float, true, false, or nil. In the :object mode the JSON should have been generated by ::dump. The parser will reconstitute the original marshalled or dumped Object. The :auto_define and :circular options have meaning with this parsing mode.

When used with a document that has multiple JSON elements the block, if any, will be yielded to. If no block then the last element read will be returned.

Raises an exception if the JSON is malformed or the classes specified are not valid. If the input is not a valid JSON document (an empty string is not a valid JSON document) an exception is raised.

Note: Oj is not able to automatically deserialize all classes that are a subclass of a Ruby Exception. Only exception that take one required string argument in the initialize() method are supported. This is an example of how to write an Exception subclass that supports both a single string intializer and an Exception as an argument. Additional optional arguments can be added as well.

The reason for this restriction has to do with a design decision on the part of the Ruby developers. Exceptions are special Objects. They do not follow the rules of other Objects. Exceptions have 'mesg' and a 'bt' attribute. Note that these are not '@mesg' and '@bt'. They can not be set using the normal C or Ruby calls. The only way I have found to set the 'mesg' attribute is through the initializer. Unfortunately that means any subclass that provides a different initializer can not be automatically decoded. A way around this is to use a create function but this example shows an alternative.

A block can also be provided with a single argument. That argument will be the parsed JSON document. This is useful when parsing a string that includes multiple JSON documents.

@param [String|IO] json JSON String or an Object that responds to read() @param [Hash] options load options (same as ::default_options)

register_odd(clas, create_object, create_method, *members) click to toggle source

Registers a class as special. This is useful for working around subclasses of primitive types as is done with ActiveSupport classes. The use of this function should be limited to just classes that can not be handled in the normal way. It is not intended as a hook for changing the output of all classes as it is not optimized for large numbers of classes.

@param [Class|Module] clas Class or Module to be made special @param [Object] create_object object to call the create method on @param [Symbol] create_method method on the clas that will create a new

instance of the clas when given all the member values in the
order specified.

@param [Symbol|String] members methods used to get the member values from

instances of the clas
static VALUE
register_odd(int argc, VALUE *argv, VALUE self) {
    if (3 > argc) {
        rb_raise(rb_eArgError, "incorrect number of arguments.");
    }
    switch (rb_type(*argv)) {
    case T_CLASS:
    case T_MODULE:
        break;
    default:
        rb_raise(rb_eTypeError, "expected a class or module.");
        break;
    }
    Check_Type(argv[2], T_SYMBOL);
    if (MAX_ODD_ARGS < argc - 2) {
        rb_raise(rb_eArgError, "too many members.");
    }
    oj_reg_odd(argv[0], argv[1], argv[2], argc - 3, argv + 3, false);

    return Qnil;
}
register_odd_raw(clas, create_object, create_method, dump_method) click to toggle source

Registers a class as special and expect the output to be a string that can be included in the dumped JSON directly. This is useful for working around subclasses of primitive types as is done with ActiveSupport classes. The use of this function should be limited to just classes that can not be handled in the normal way. It is not intended as a hook for changing the output of all classes as it is not optimized for large numbers of classes. Be careful with this option as the JSON may be incorrect if invalid JSON is returned.

@param [Class|Module] clas Class or Module to be made special @param [Object] create_object object to call the create method on @param [Symbol] create_method method on the clas that will create a new

instance of the clas when given all the member values in the
order specified.

@param [Symbol|String] dump_method method to call on the object being

serialized to generate the raw JSON.
static VALUE
register_odd_raw(int argc, VALUE *argv, VALUE self) {
    if (3 > argc) {
        rb_raise(rb_eArgError, "incorrect number of arguments.");
    }
    switch (rb_type(*argv)) {
    case T_CLASS:
    case T_MODULE:
        break;
    default:
        rb_raise(rb_eTypeError, "expected a class or module.");
        break;
    }
    Check_Type(argv[2], T_SYMBOL);
    if (MAX_ODD_ARGS < argc - 2) {
        rb_raise(rb_eArgError, "too many members.");
    }
    oj_reg_odd(argv[0], argv[1], argv[2], 1, argv + 3, true);

    return Qnil;
}
safe_load(doc) click to toggle source

Loads a JSON document in strict mode with :auto_define and :symbol_keys turned off. This function should be safe to use with JSON received on an unprotected public interface.

@param [String|IO] doc JSON String or IO to load @return [Hash|Array|String|Fixnum|Bignum|BigDecimal|nil|True|False]

static VALUE
safe_load(VALUE self, VALUE doc) {
    struct _ParseInfo   pi;
    VALUE               args[1];

    pi.err_class = Qnil;
    pi.options = oj_default_options;
    pi.options.auto_define = No;
    pi.options.sym_key = No;
    pi.options.mode = StrictMode;
    oj_set_strict_callbacks(&pi);
    *args = doc;

    return oj_pi_parse(1, args, &pi, 0, 0, 1);
}
strict_load(json, options) → Hash, Array, String, Fixnum, Float, true, false, or nil

Parses a JSON document String into an Hash, Array, String, Fixnum, Float, true, false, or nil. It parses using a mode that is strict in that it maps each primitive JSON type to a similar Ruby type. The :create_id is not honored in this mode. Note that a Ruby Hash is used to represent the JSON Object type. These two are not the same since the JSON Object type can have repeating entries with the same key and Ruby Hash can not.

When used with a document that has multiple JSON elements the block, if any, will be yielded to. If no block then the last element read will be returned.

Raises an exception if the JSON is malformed or the classes specified are not valid. If the input is not a valid JSON document (an empty string is not a valid JSON document) an exception is raised.

A block can also be provided with a single argument. That argument will be the parsed JSON document. This is useful when parsing a string that includes multiple JSON documents.

@param [String|IO] json JSON String or an Object that responds to read() @param [Hash] options load options (same as ::default_options)

to_file(file_path, obj, options) click to toggle source

Dumps an Object to the specified file. @param [String] file_path file path to write the JSON document to @param [Object] obj Object to serialize as an JSON document String @param [Hash] options formating options @param [Fixnum] :indent format expected @param [true|false] :circular allow circular references, default: false

static VALUE
to_file(int argc, VALUE *argv, VALUE self) {
    struct _Options     copts = oj_default_options;
    
    if (3 == argc) {
        oj_parse_options(argv[2], &copts);
    }
    Check_Type(*argv, T_STRING);
    oj_write_obj_to_file(argv[1], StringValuePtr(*argv), &copts);

    return Qnil;
}
to_stream(io, obj, options) click to toggle source

Dumps an Object to the specified IO stream. @param [IO] io IO stream to write the JSON document to @param [Object] obj Object to serialize as an JSON document String @param [Hash] options formating options @param [Fixnum] :indent format expected @param [true|false] :circular allow circular references, default: false

static VALUE
to_stream(int argc, VALUE *argv, VALUE self) {
    struct _Options     copts = oj_default_options;
    
    if (3 == argc) {
        oj_parse_options(argv[2], &copts);
    }
    oj_write_obj_to_stream(argv[1], *argv, &copts);

    return Qnil;
}

Public Instance Methods

as_json(*) click to toggle source
# File lib/oj/mimic.rb, line 50
def as_json(*)
  name = self.class.name.to_s
  raise JSON::JSONError, "Only named structs are supported!" if 0 == name.length
  { JSON.create_id => name, 't' => table }
end