Method: Oj.to_json

Defined in:
ext/oj/oj.c

.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.

[View source]

1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
# File 'ext/oj/oj.c', line 1353

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