Module: Oj

Defined in:
lib/oj.rb,
lib/oj/bag.rb,
lib/oj/saj.rb,
lib/oj/error.rb,
lib/oj/mimic.rb,
lib/oj/version.rb,
lib/oj/easy_hash.rb,
lib/oj/schandler.rb,
lib/oj/active_support_helper.rb,
ext/oj/oj.c,
ext/oj/oj.c

Overview

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

Oj uses modes to control how object are encoded and decoded. In addition global and options to methods allow additional behavior modifications. The modes are:

  • :strict mode will only allow the 7 basic JSON types to be serialized. Any other Object will raise an Exception.

  • :null mode is similar to the :strict mode except any Object that is not one of the JSON base types is replaced by a JSON null.

  • :object mode will dump any Object as a JSON Object with keys that match the Ruby Object's variable names without the '@' character. This is the highest performance mode.

  • :compat or :json mode is the compatible mode for the json gem. It mimics the json gem including the options, defaults, and restrictions.

  • :rails is the compatibility mode for Rails or Active support.

  • :custom is the most configurable mode.

  • :wab specifically for WAB data exchange.

Defined Under Namespace

Modules: Rails Classes: ActiveSupportHelper, Bag, CStack, Cache, Doc, EasyHash, MimicDumpOption, Parser, Saj, ScHandler, StreamWriter, StringWriter

Constant Summary collapse

Error =

Inherit Error class from StandardError.

Class.new(StandardError)
ParseError =

An Exception that is raised as a result of a parse error while parsing a JSON document.

Class.new(Error)
DepthError =

An Exception that is raised as a result of a path being too deep.

Class.new(Error)
LoadError =

An Exception that is raised if a file fails to load.

Class.new(Error)
MimicError =

An Exception that is raised if there is a conflict with mimicking JSON

Class.new(Error)
CUSTOM_MIMIC_JSON_OPTIONS =

Custom mode can be used to emulate the compat mode with some minor differences. These are the options that setup the custom mode to be like the compat mode.

{
  allow_gc: true,
  allow_invalid_unicode: false,
  allow_nan: false,
  array_class: nil,
  array_nl: nil,
  auto_define: false,
  bigdecimal_as_decimal: false,
  bigdecimal_load: :auto,
  circular: false,
  class_cache: false,
  cache_keys: true,
  cache_str: 5,
  create_additions: false,
  create_id: "json_class",
  empty_string: false,
  escape_mode: :unicode_xss,
  float_precision: 0,
  hash_class: nil,
  ignore: nil,
  ignore_under: false,
  indent: 0,
  integer_range: nil,
  mode: :custom,
  nan: :raise,
  nilnil: false,
  object_nl: nil,
  omit_nil: false,
  quirks_mode: true,
  safe: false,
  second_precision: 3,
  space: nil,
  space_before: nil,
  symbol_keys: false,
  time_format: :ruby,
  trace: false,
  use_as_json: false,
  use_raw_json: false,
  use_to_hash: false,
  use_to_json: true,
}
VERSION =

Current version of the module.

'3.17.5'

Class Method Summary collapse

Class Method Details

.add_to_jsonObject



2026
# File 'ext/oj/oj.c', line 2026

extern VALUE oj_add_to_json(int argc, VALUE *argv, VALUE self);

.compat_loadObject



1944
# File 'ext/oj/oj.c', line 1944

extern VALUE oj_compat_parse(int argc, VALUE *argv, VALUE self);

.debug_odd(label) ⇒ Object

rb_define_module_function(Oj, "hash_test", hash_test, 0);



2116
2117
2118
2119
# File 'ext/oj/oj.c', line 2116

static VALUE debug_odd(VALUE self, VALUE label) {
    print_all_odds(RSTRING_PTR(label));
    return Qnil;
}

.default_optionsObject



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
# File 'ext/oj/oj.c', line 356

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, oj_indent_sym, INT2FIX(oj_default_options.indent));
    } else {
        rb_hash_aset(opts, oj_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,
        oj_create_additions_sym,
        (Yes == oj_default_options.create_ok) ? Qtrue : ((No == oj_default_options.create_ok) ? 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_to_hash_sym,
                 (Yes == oj_default_options.to_hash) ? Qtrue : ((No == oj_default_options.to_hash) ? 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,
                 use_raw_json_sym,
                 (Yes == oj_default_options.raw_json) ? Qtrue : ((No == oj_default_options.raw_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,
        empty_string_sym,
        (Yes == oj_default_options.empty_string) ? Qtrue : ((No == oj_default_options.empty_string) ? 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,
        oj_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,
        oj_allow_nan_sym,
        (Yes == oj_default_options.allow_nan) ? Qtrue : ((No == oj_default_options.allow_nan) ? Qfalse : Qnil));
    rb_hash_aset(opts,
                 oj_trace_sym,
                 (Yes == oj_default_options.trace) ? Qtrue : ((No == oj_default_options.trace) ? Qfalse : Qnil));
    rb_hash_aset(opts,
                 oj_safe_sym,
                 (Yes == oj_default_options.safe) ? Qtrue : ((No == oj_default_options.safe) ? Qfalse : Qnil));
    rb_hash_aset(opts, float_prec_sym, INT2FIX(oj_default_options.float_prec));
    rb_hash_aset(opts, float_format_sym, rb_str_new_cstr(oj_default_options.float_fmt));
    rb_hash_aset(opts, cache_str_sym, INT2FIX(oj_default_options.cache_str));
    rb_hash_aset(
        opts,
        ignore_under_sym,
        (Yes == oj_default_options.ignore_under) ? Qtrue : ((No == oj_default_options.ignore_under) ? Qfalse : Qnil));
    rb_hash_aset(
        opts,
        cache_keys_sym,
        (Yes == oj_default_options.cache_keys) ? Qtrue : ((No == oj_default_options.cache_keys) ? Qfalse : Qnil));

    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: rb_hash_aset(opts, mode_sym, object_sym); break;
    case CustomMode: rb_hash_aset(opts, mode_sym, custom_sym); break;
    case RailsMode: rb_hash_aset(opts, mode_sym, rails_sym); break;
    case WabMode: rb_hash_aset(opts, mode_sym, wab_sym); break;
    default: rb_hash_aset(opts, mode_sym, object_sym); break;
    }

    if (oj_default_options.int_range_max != 0 || oj_default_options.int_range_min != 0) {
        VALUE range = rb_obj_alloc(rb_cRange);
        VALUE min   = LONG2FIX(oj_default_options.int_range_min);
        VALUE max   = LONG2FIX(oj_default_options.int_range_max);

        rb_ivar_set(range, oj_begin_id, min);
        rb_ivar_set(range, oj_end_id, max);
        rb_hash_aset(opts, integer_range_sym, range);
    } else {
        rb_hash_aset(opts, integer_range_sym, Qnil);
    }
    rb_hash_aset(opts, max_integer_digits_sym, LONG2NUM((long)oj_default_options.max_integer_digits));
    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 SlashEsc: rb_hash_aset(opts, escape_mode_sym, slash_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;
    case JXEsc: rb_hash_aset(opts, escape_mode_sym, unicode_xss_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 FastDec: rb_hash_aset(opts, bigdecimal_load_sym, fast_sym); break;
    case AutoDec:
    default: rb_hash_aset(opts, bigdecimal_load_sym, auto_sym); break;
    }
    rb_hash_aset(opts, compat_bigdecimal_sym, oj_default_options.compat_bigdec ? Qtrue : Qfalse);
    rb_hash_aset(opts,
                 create_id_sym,
                 (NULL == oj_default_options.create_id) ? Qnil : rb_str_new2(oj_default_options.create_id));
    rb_hash_aset(
        opts,
        oj_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,
        oj_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,
        oj_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,
        oj_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, omit_null_byte_sym, oj_default_options.dump_opts.omit_null_byte ? Qtrue : Qfalse);
    rb_hash_aset(opts, oj_hash_class_sym, oj_default_options.hash_class);
    rb_hash_aset(opts, oj_array_class_sym, oj_default_options.array_class);

    rb_hash_aset(opts, only_sym, only_array_from_string(oj_default_options.dump_opts.only));
    rb_hash_aset(opts, except_sym, only_array_from_string(oj_default_options.dump_opts.except));

    if (NULL == oj_default_options.ignore) {
        rb_hash_aset(opts, ignore_sym, Qnil);
    } else {
        VALUE         *vp;
        volatile VALUE a = rb_ary_new();

        for (vp = oj_default_options.ignore; Qnil != *vp; vp++) {
            rb_ary_push(a, *vp);
        }
        rb_hash_aset(opts, ignore_sym, a);
    }
    return opts;
}

.default_options=(opts) ⇒ Object



645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
# File 'ext/oj/oj.c', line 645

static VALUE set_def_opts(VALUE self, VALUE opts) {
    Check_Type(opts, T_HASH);
    // A :match_string option replaces the regexps instead of adding to them so
    // the ones the defaults are holding have to be freed here, the only place
    // that owns them. A per call options struct only aliases them.
    if (Qnil != rb_hash_lookup(opts, match_string_sym)) {
        oj_rxclass_cleanup(&oj_default_options.str_rx);
        oj_default_options.str_rx.head = NULL;
        oj_default_options.str_rx.tail = NULL;
    }
    oj_parse_options(opts, &oj_default_options);
    keep_default_options();

    return Qnil;
}

.dump(*args) ⇒ Object



1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
# File 'ext/oj/oj.c', line 1670

static VALUE dump(int argc, VALUE *argv, VALUE self) {
    struct dump_arg arg;
    struct _out     out;
    struct _options copts = oj_default_options;

    if (1 > argc) {
        rb_raise(rb_eArgError, "wrong number of arguments (0 for 1).");
    }
    if (CompatMode == copts.mode) {
        copts.dump_opts.nan_dump = WordNan;
    }
    if (2 == argc) {
        oj_parse_options(argv[1], &copts);
    }
    if (CompatMode == copts.mode && copts.escape_mode != ASCIIEsc) {
        copts.escape_mode = JSONEsc;
    }
    arg.out   = &out;
    arg.copts = &copts;
    arg.argc  = argc;
    arg.argv  = argv;

    oj_out_init(arg.out);

    arg.out->omit_nil       = copts.dump_opts.omit_nil;
    arg.out->omit_null_byte = copts.dump_opts.omit_null_byte;

    return rb_ensure(dump_body, (VALUE)&arg, dump_ensure, (VALUE)&arg);
}

.fast_generateObject



2082
# File 'ext/oj/oj.c', line 2082

extern VALUE oj_mimic_generate(int argc, VALUE *argv, VALUE self);

.generateObject



2082
# File 'ext/oj/oj.c', line 2082

extern VALUE oj_mimic_generate(int argc, VALUE *argv, VALUE self);

.load(*args) ⇒ Object



1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
# File 'ext/oj/oj.c', line 1430

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;

        if (Qnil != ropts || CompatMode != mode) {
            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 || json_sym == v) {
                    mode = CompatMode;
                } else if (null_sym == v) {
                    mode = NullMode;
                } else if (custom_sym == v) {
                    mode = CustomMode;
                } else if (rails_sym == v) {
                    mode = RailsMode;
                } else if (wab_sym == v) {
                    mode = WabMode;
                } else {
                    rb_raise(rb_eArgError,
                             ":mode must be :object, :strict, :compat, :null, :custom, :rails, or "
                             ":wab.");
                }
            }
        }
    }
    switch (mode) {
    case StrictMode:
    case NullMode: return oj_strict_parse(argc, argv, self);
    case CompatMode:
    case RailsMode: return oj_compat_parse(argc, argv, self);
    case CustomMode: return oj_custom_parse(argc, argv, self);
    case WabMode: return oj_wab_parse(argc, argv, self);
    case ObjectMode:
    default: break;
    }
    return oj_object_parse(argc, argv, self);
}

.load_file(*args) ⇒ Object



1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
# File 'ext/oj/oj.c', line 1512

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().");
    }
    path = StringValuePtr(*argv);
    parse_info_init(&pi);
    pi.options   = oj_default_options;
    pi.handler   = Qnil;
    pi.err_class = Qnil;
    pi.max_depth = 0;
    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 || json_sym == v) {
                mode = CompatMode;
            } else if (null_sym == v) {
                mode = NullMode;
            } else if (custom_sym == v) {
                mode = CustomMode;
            } else if (rails_sym == v) {
                mode = RailsMode;
            } else if (wab_sym == v) {
                mode = WabMode;
            } else {
                rb_raise(rb_eArgError, ":mode must be :object, :strict, :compat, :null, :custom, :rails, or :wab.");
            }
        }
    }
#ifdef _WIN32
    {
        WCHAR *wide_path;
        wide_path = rb_w32_mbstr_to_wstr(CP_UTF8, path, -1, NULL);
        fd        = rb_w32_wopen(wide_path, O_RDONLY);
        OJ_FREE(wide_path);
    }
#else
    fd = open(path, O_RDONLY);
#endif
    if (0 == fd) {
        rb_raise(rb_eIOError, "%s", strerror(errno));
    }
    switch (mode) {
    case StrictMode:
    case NullMode: oj_set_strict_callbacks(&pi); return oj_pi_sparse(argc, argv, &pi, fd);
    case CustomMode: oj_set_custom_callbacks(&pi); return oj_pi_sparse(argc, argv, &pi, fd);
    case CompatMode:
    case RailsMode: oj_set_compat_callbacks(&pi); return oj_pi_sparse(argc, argv, &pi, fd);
    case WabMode: oj_set_wab_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);
}

.mem_reportObject



2121
2122
2123
2124
# File 'ext/oj/oj.c', line 2121

static VALUE mem_report(VALUE self) {
    oj_mem_report();
    return Qnil;
}

.mimic_JSONObject



2060
# File 'ext/oj/oj.c', line 2060

extern VALUE oj_define_mimic_json(int argc, VALUE *argv, VALUE self);

.mimic_loaded(mimic_paths = []) ⇒ Object

Loads mimic-ed JSON paths. Used by Oj.mimic_JSON().

Parameters:

  • mimic_paths (Array) (defaults to: [])

    additional paths to add to the Ruby loaded features.



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/oj/mimic.rb', line 80

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|
      # allow json/add/xxx to be loaded. User can override with Oj.add_to_json(xxx).
      $LOADED_FEATURES << file unless $LOADED_FEATURES.include?(file) unless file.include?('add')
    end
  end
  mimic_paths.each { |p| $LOADED_FEATURES << p }
  $LOADED_FEATURES << 'json' unless $LOADED_FEATURES.include?('json')

  require 'oj/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'] || h[:t])
      end
    end
  end

  BigDecimal.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 => 'BigDecimal', 'b' => _dump }
      end
    end
    def self.json_create(h)
      BigDecimal._load(h['b'])
    end
  end

  Complex.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 => 'Complex', 'r' => real, 'i' => imag }
      end
    end
    def self.json_create(h)
      Complex(h['r'], h['i'])
    end
  end

  DateTime.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 => 'DateTime',
          'y' => year,
          'm' => month,
          'd' => day,
          'H' => hour,
          'M' => min,
          'S' => sec,
          'of' => offset.to_s,
          'sg' => start }
      end
    end
    def self.json_create(h)
      # offset is a rational as a string
      as, bs = h['of'].split('/')
      a = as.to_i
      b = bs.to_i
      if 0 == b
        off = a
      else
        off = Rational(a, b)
      end
      civil(h['y'], h['m'], h['d'], h['H'], h['M'], h['S'], off, h['sg'])
    end
  end

  Date.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 => 'Date', 'y' => year, 'm' => month, 'd' => day, 'sg' => start }
      end
    end
    def self.json_create(h)
      civil(h['y'], h['m'], h['d'], h['sg'])
    end
  end

  Exception.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 => self.class.name, 'm' => message, 'b' => backtrace }
      end
    end
    def self.json_create(h)
      e = new(h['m'])
      e.set_backtrace(h['b'])
      e
    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(*)
        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
end

.object_loadObject



1974
# File 'ext/oj/oj.c', line 1974

extern VALUE oj_object_parse(int argc, VALUE *argv, VALUE self);

.optimize_railsObject



2089
# File 'ext/oj/oj.c', line 2089

extern VALUE oj_optimize_rails(VALUE self);

.register_odd(*args) ⇒ Object



1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
# File 'ext/oj/oj.c', line 1817

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(*args) ⇒ Object



1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
# File 'ext/oj/oj.c', line 1853

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;
}

.remove_to_jsonObject



2042
# File 'ext/oj/oj.c', line 2042

extern VALUE oj_remove_to_json(int argc, VALUE *argv, VALUE self);

.safe_load(doc) ⇒ Object



1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
# File 'ext/oj/oj.c', line 1591

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

    parse_info_init(&pi);
    pi.err_class           = Qnil;
    pi.max_depth           = 0;
    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);
}

.saj_parseObject

.sc_parseObject

.strict_loadObject



1910
# File 'ext/oj/oj.c', line 1910

extern VALUE oj_strict_parse(int argc, VALUE *argv, VALUE self);

.to_file(*args) ⇒ Object



1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
# File 'ext/oj/oj.c', line 1767

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);
    }
    oj_write_obj_to_file(argv[1], StringValuePtr(*argv), &copts);
    oj_free_call_options(&copts);

    return Qnil;
}

.to_json(obj, options) ⇒ Object

Dumps an Object (obj) to a string. If the object has a to_json method that will be called. The mode is set to :compat.

  • obj [Object] Object to serialize as an JSON document String
  • options [Hash]
    • :max_nesting [Fixnum|boolean] It true nesting is limited to 100. If a Fixnum nesting is set to the provided value. The option to detect circular references is available but is not compatible with the json gem., default is false or unlimited.
    • :allow_nan [boolean] If true non JSON compliant words such as Nan and Infinity will be used as appropriate, default is true.
    • :quirks_mode [boolean] Allow single JSON values instead of documents, default is true (allow).
    • :indent [String|nil] String to use for indentation, overriding the indent option if 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.
    • :trace [Boolean] If true trace is turned on.

Returns [String] the encoded JSON.



1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
# File 'ext/oj/oj.c', line 1723

static VALUE to_json(int argc, VALUE *argv, VALUE self) {
    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).");
    }
    copts.escape_mode        = JXEsc;
    copts.dump_opts.nan_dump = RaiseNan;
    if (2 == argc) {
        oj_parse_mimic_dump_options(argv[1], &copts);
    }
    copts.mode    = CompatMode;
    copts.to_json = Yes;

    oj_out_init(&out);

    out.omit_nil       = copts.dump_opts.omit_nil;
    out.omit_null_byte = copts.dump_opts.omit_null_byte;
    // For obj.to_json or generate nan is not allowed but if called from dump
    // it is.
    oj_dump_obj_to_json_using_params(*argv, &copts, &out, argc - 1, argv + 1);

    if (0 == out.buf) {
        rb_raise(rb_eNoMemError, "Not enough memory.");
    }
    rstr = rb_utf8_str_new_cstr(out.buf);

    oj_out_free(&out);

    return rstr;
}

.to_stream(*args) ⇒ Object



1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
# File 'ext/oj/oj.c', line 1789

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);
    oj_free_call_options(&copts);

    return Qnil;
}

.wab_loadObject



2009
# File 'ext/oj/oj.c', line 2009

extern VALUE oj_wab_parse(int argc, VALUE *argv, VALUE self);