Module: Oj
- Defined in:
- ext/oj/oj.c,
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
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, Doc, EasyHash, MimicDumpOption, 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 mimicing JSON
Class.new(Error)
- VERSION =
Current version of the module.
'3.10.12'
Class Method Summary collapse
-
.add_to_json(*args) ⇒ Object
Override simple to_s dump behavior in :compat mode to instead use an optimized dump that includes the classname and attributes so that the object can be re-created on load.
-
.compat_load(json, options) { ... } ⇒ Object
Parses a JSON document String into an Object, Hash, Array, String, Fixnum, Float, true, false, or nil.
-
.default_options ⇒ Object
Returns the default load and dump options as a Hash.
-
.default_options=(opts) ⇒ Object
Sets the default options for load and dump.
-
.dump(obj, options = {}) ⇒ Object
Dumps an Object (obj) to a string.
-
.generate(obj, opts = nil) ⇒ Object
Encode obj as a JSON String.
-
.generate(obj, opts = nil) ⇒ Object
Encode obj as a JSON String.
-
.load(json, options = ) { ... } ⇒ Object
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.
-
.load_file(path, options = ) { ... } ⇒ Object
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.
-
.mimic_JSON ⇒ Object
Creates the JSON module with methods and classes to mimic the JSON gem.
-
.mimic_loaded(mimic_paths = []) ⇒ Object
Loads mimic-ed JSON paths.
-
.object_load(json, options) { ... } ⇒ Object
Parses a JSON document String into an Object, Hash, Array, String, Fixnum, Float, true, false, or nil.
-
.optimize_rails ⇒ Object
Sets the Oj as the Rails encoder and decoder.
-
.register_odd(clas, create_object, create_method, *members) ⇒ Object
Registers a class as special.
-
.register_odd_raw(clas, create_object, create_method, dump_method) ⇒ Object
Registers a class as special and expect the output to be a string that can be included in the dumped JSON directly.
-
.remove_to_json ⇒ Object
Reverts back to the to_s dump behavior in :compat mode to instead use an optimized dump that includes the classname and attributes so that the object can be re-created on load.
-
.safe_load(doc) ⇒ Object
Loads a JSON document in strict mode with :auto_define and :symbol_keys turned off.
-
.saj_parse(handler, io) ⇒ Object
Parses an IO stream or file containing a JSON document.
-
.sc_parse(handler, io) ⇒ Object
Parses an IO stream or file containing a JSON document.
-
.strict_load(json, options) { ... } ⇒ Object
Parses a JSON document String into an Hash, Array, String, Fixnum, Float, true, false, or nil.
-
.to_file(file_path, obj, options = {}) ⇒ Object
Dumps an Object to the specified file.
-
.to_json(obj, options) ⇒ Object
Dumps an Object (obj) to a string.
-
.to_stream(io, obj, options = {}) ⇒ Object
Dumps an Object to the specified IO stream.
-
.wab_load(json, options) { ... } ⇒ Object
Parses a JSON document String into an Hash, Array, String, Fixnum, Float, true, false, or nil.
Class Method Details
.add_to_json(*args) ⇒ Object
Override simple to_s dump behavior in :compat mode to instead use an optimized dump that includes the classname and attributes so that the object can be re-created on load. The format is the same as the json gem but does not use the ruby methods for encoding.
The classes supported for optimization are: Array, BigDecimal, Complex, Date, DateTime, Exception, Hash, Integer, OpenStruct, Range, Rational, Regexp, Struct, and Time. Providing no classes will result in all those classes being optimized.q
-
*args( [Class] zero or more classes to optimize.
1423 |
# File 'ext/oj/oj.c', line 1423
extern VALUE oj_add_to_json(int argc, VALUE *argv, VALUE self);
|
.compat_load(json, options) { ... } ⇒ Object
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 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. The block can take up to 3 arguments, the parsed object, the position in the string or stream of the start of the JSON for that object, and the length of the JSON for that object plus trailing whitespace.
-
json [String|IO] JSON String or an Object that responds to read().
-
options [Hash] load options (same as default_options).
-
obj [Hash|Array|String|Fixnum|Float|Boolean|nil] parsed object.
-
start [_optional, Integer] start position of parsed JSON for obj.
-
len [_optional, Integer] length of parsed JSON for obj.
Returns [Hash|Array|String|Fixnum|Float|Boolean|nil]
1341 |
# File 'ext/oj/oj.c', line 1341
extern VALUE oj_compat_parse(int argc, VALUE *argv, VALUE self);
|
.default_options ⇒ Object
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 [Boolean|nil] support circular references while dumping
-
:auto_define [Boolean|nil] automatically define classes if they do not exist
-
:symbol_keys [Boolean|nil] use symbols instead of strings for hash keys
-
:escape_mode [:newline|:json|:xss_safe|:ascii|unicode_xss|nil] determines the characters to escape
-
:class_cache [Boolean|nil] cache classes for faster parsing (if dynamically modifying classes or reloading classes then don't use this)
-
:mode [:object|:strict|:compat|:null|:custom|:rails|:wab] load and dump modes to use for JSON
-
:time_format [:unix|:unix_zone|:xmlschema|:ruby] time format when dumping
-
:bigdecimal_as_decimal [Boolean|nil] dump BigDecimal as a decimal number or as a String
-
:bigdecimal_load [:bigdecimal|:float|:auto|:fast] load decimals as BigDecimal instead of as a Float. :auto pick the most precise for the number of digits. :float should be the same as ruby. :fast may require rounding but is must faster.
-
:create_id [String|nil] create id for json compatible object encoding, default is 'json_class'
-
:create_additions [Boolean|nil] if true allow creation of instances using create_id on load.
-
: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 [Boolean|nil] call to_json() methods on dump, default is false
-
:use_as_json [Boolean|nil] call as_json() methods on dump, default is false
-
:use_raw_json [Boolean|nil] call raw_json() methods on dump, default is false
-
:nilnil [Boolean|nil] if true a nil input to load will return nil and not raise an Exception
-
:empty_string [Boolean|nil] if true an empty input will not raise an Exception
-
:allow_gc [Boolean|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)
-
:allow_nan [true,|false|nil] Allow Nan, Infinity, and -Infinity to be parsed, default is true (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. :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, :object_class can also be used
-
:array_class [Class|nil] Class to use instead of Array on load
-
:omit_nil [true|false] if true Hash and Object attributes with nil values are omitted
-
:ignore [nil|Array] either nil or an Array of classes to ignore when dumping
-
:ignore_under [Boolean] if true then attributes that start with _ are ignored when dumping in object or custom mode.
-
:integer_range [Range] Dump integers outside range as strings.
-
:trace [true,|false] Trace all load and dump calls, default is false (trace is off)
-
:safe [true,|false] Safe mimic breaks JSON mimic to be safer, default is false (safe is off)
Return [Hash] all current option settings.
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
# File 'ext/oj/oj.c', line 265
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, ignore_under_sym, (Yes == oj_default_options.ignore_under) ? Qtrue : ((No == oj_default_options.ignore_under) ? 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);
}
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;
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, 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, oj_hash_class_sym, oj_default_options.hash_class);
rb_hash_aset(opts, oj_array_class_sym, oj_default_options.array_class);
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
Sets the default options for load and dump.
-
opts [Hash] options to change
-
:indent [Fixnum|String|nil] number of spaces to indent each element in a JSON document or the String to use for identation.
-
:circular [Boolean|nil] support circular references while dumping.
-
:auto_define [Boolean|nil] automatically define classes if they do not exist.
-
:symbol_keys [Boolean|nil] convert hash keys to symbols.
-
:class_cache [Boolean|nil] cache classes for faster parsing.
-
:escape [:newline|:json|:xss_safe|:ascii|unicode_xss|nil] 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, :unicode_xss allows unicode but escapes &, <, and >, and any u20xx characters along with some others, and :xss_safe escapes &, <, and >, and some others.
-
:bigdecimal_as_decimal [Boolean|nil] dump BigDecimal as a decimal number or as a String.
-
:bigdecimal_load [:bigdecimal|:float|:auto|nil] load decimals as BigDecimal instead of as a Float. :auto pick the most precise for the number of digits.
-
:mode [:object|:strict|:compat|:null|:custom|:rails|:wab] 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. The :custom mode honors all dump options. The :rails more mimics rails and Active behavior.
-
:time_format [: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.
-
:create_id [String|nil] create id for json compatible object encoding
-
:create_additions [Boolean|nil] if true allow creation of instances using create_id on load.
-
: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 [Boolean|nil] call to_json() methods on dump, default is false.
-
:use_as_json [Boolean|nil] call as_json() methods on dump, default is false.
-
:use_to_hash [Boolean|nil] call to_hash() methods on dump, default is false.
-
:use_raw_json [Boolean|nil] call raw_json() methods on dump, default is false.
-
:nilnil [Boolean|nil] if true a nil input to load will return nil and not raise an Exception.
-
:allow_gc [Boolean|nil] allow or prohibit GC during parsing, default is true (allow).
-
:quirks_mode [Boolean|nil] allow single JSON values instead of documents, default is true (allow).
-
:allow_invalid_unicode [Boolean|nil] allow invalid unicode, default is false (don't allow).
-
:allow_nan [Boolean|nil] allow Nan, Infinity, and -Infinity, default is true (allow).
-
: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] 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, :object_class can also be used.
-
:array_class [Class|nil] Class to use instead of Array on load.
-
:omit_nil [true|false] if true Hash and Object attributes with nil values are omitted.
-
:ignore [nil|Array] either nil or an Array of classes to ignore when dumping
-
:ignore_under [Boolean] if true then attributes that start with _ are ignored when dumping in object or custom mode.
-
:integer_range [Range] Dump integers outside range as strings.
-
:trace [Boolean] turn trace on or off.
-
:safe [Boolean] turn safe mimic on or off.
-
413 414 415 416 417 418 419 |
# File 'ext/oj/oj.c', line 413
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, options = {}) ⇒ Object
Dumps an Object (obj) to a string.
-
obj [Object] Object to serialize as an JSON document String
-
options [Hash] same as default_options
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 |
# File 'ext/oj/oj.c', line 1058
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 (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;
}
out.buf = buf;
out.end = buf + sizeof(buf) - 10;
out.allocated = false;
out.omit_nil = copts.dump_opts.omit_nil;
out.caller = CALLER_DUMP;
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_str_new2(out.buf);
rstr = oj_encode(rstr);
if (out.allocated) {
xfree(out.buf);
}
return rstr;
}
|
.generate(obj, opts = nil) ⇒ Object
Encode obj as a JSON String. The obj argument must be a Hash, Array, or respond to to_h or to_json. Options other than those listed such as :allow_nan
or :max_nesting
are ignored.
-
obj [Object_|Hash|Array] object to convert to a JSON String
-
opts [Hash] options
-
:indent [String] String to use for indentation.
-
:space [String] String placed after a , or : delimiter
-
:space_before [String] String placed before a : delimiter
-
:object_nl [String] String placed after a JSON object
-
:array_nl [String] String placed after a JSON array
-
:ascii_only [Boolean] if not nil or false then use only ascii characters in the output. Note JSON.generate does support this even if it is not documented.
-
Returns [String]generated JSON.
1477 |
# File 'ext/oj/oj.c', line 1477
extern VALUE oj_mimic_generate(int argc, VALUE *argv, VALUE self);
|
.generate(obj, opts = nil) ⇒ Object
Encode obj as a JSON String. The obj argument must be a Hash, Array, or respond to to_h or to_json. Options other than those listed such as :allow_nan
or :max_nesting
are ignored.
-
obj [Object_|Hash|Array] object to convert to a JSON String
-
opts [Hash] options
-
:indent [String] String to use for indentation.
-
:space [String] String placed after a , or : delimiter
-
:space_before [String] String placed before a : delimiter
-
:object_nl [String] String placed after a JSON object
-
:array_nl [String] String placed after a JSON array
-
:ascii_only [Boolean] if not nil or false then use only ascii characters in the output. Note JSON.generate does support this even if it is not documented.
-
Returns [String]generated JSON.
1477 |
# File 'ext/oj/oj.c', line 1477
extern VALUE oj_mimic_generate(int argc, VALUE *argv, VALUE self);
|
.load(json, options = ) { ... } ⇒ Object
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.
This parser operates on string and will attempt to load files into memory if a file object is passed as the first argument. A stream input will be parsed using a stream parser but others use the slightly faster string parser.
A block can 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. The block can take up to 3 arguments, the parsed object, the position in the string or stream of the start of the JSON for that object, and the length of the JSON for that object plus trailing whitespace.
-
json [String|IO] JSON String or an Object that responds to read()
-
options [Hash] load options (same as default_options)
-
obj [Hash|Array|String|Fixnum|Float|Boolean|nil] parsed object.
-
start [_optional, Integer] start position of parsed JSON for obj.
-
len [_optional, Integer] length of parsed JSON for obj.
Returns [Hash|Array|String|Fixnum|Float|Boolean|nil]
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 |
# File 'ext/oj/oj.c', line 841
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(path, options = ) { ... } ⇒ Object
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 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. The block can take up to 3 arguments, the parsed object, the position in the string or stream of the start of the JSON for that object, and the length of the JSON for that object plus trailing whitespace.
-
path [String] to a file containing a JSON document
-
options [Hash] load options (same as default_options)
-
obj [Hash|Array|String|Fixnum|Float|Boolean|nil] parsed object.
-
start [_optional, Integer] start position of parsed JSON for obj.
-
len [_optional, Integer] length of parsed JSON for obj.
Returns [Object|Hash|Array|String|Fixnum|Float|Boolean|nil]
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 |
# File 'ext/oj/oj.c', line 927
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);
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.");
}
}
}
path = StringValuePtr(*argv);
if (0 == (fd = open(path, O_RDONLY))) {
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);
}
|
.mimic_JSON ⇒ Object
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 :unicode_xss.
Returns [Module] the JSON module.
1457 |
# File 'ext/oj/oj.c', line 1457
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().
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 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 |
# File 'lib/oj/mimic.rb', line 35 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 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 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' => , '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' => , '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_load(json, options) { ... } ⇒ Object
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 Oj.dump(). The parser will reconstitute the original marshalled or dumped Object. The :auto_define and :circular options have meaning with this parsing mode.
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 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. The block can take up to 3 arguments, the parsed object, the position in the string or stream of the start of the JSON for that object, and the length of the JSON for that object plus trailing whitespace.
-
json [String|IO] JSON String or an Object that responds to read().
-
options [Hash] load options (same as default_options).
-
obj [Hash|Array|String|Fixnum|Float|Boolean|nil] parsed object.
-
start [_optional, Integer] start position of parsed JSON for obj.
-
len [_optional, Integer] length of parsed JSON for obj.
Returns [Hash|Array|String|Fixnum|Float|Boolean|nil]
1371 |
# File 'ext/oj/oj.c', line 1371
extern VALUE oj_object_parse(int argc, VALUE *argv, VALUE self);
|
.optimize_rails ⇒ Object
Sets the Oj as the Rails encoder and decoder. Oj::Rails.optimize is also called.
1484 |
# File 'ext/oj/oj.c', line 1484 extern VALUE oj_optimize_rails(VALUE self); |
.register_odd(clas, create_object, create_method, *members) ⇒ Object
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.
-
clas [Class_|Module] Class or Module to be made special
-
create_object [Object] object to call the create method on
-
create_method [Symbol] method on the clas that will create a new instance of the clas when given all the member values in the order specified.
-
members [Symbol_|String] methods used to get the member values from instances of the clas.
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 |
# File 'ext/oj/oj.c', line 1208
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) ⇒ Object
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.
-
clas [Class|Module] Class or Module to be made special
-
create_object [Object] object to call the create method on
-
create_method [Symbol] method on the clas that will create a new instance of the clas when given all the member values in the order specified.
-
dump_method [Symbol|String] method to call on the object being serialized to generate the raw JSON.
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 |
# File 'ext/oj/oj.c', line 1246
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_json ⇒ Object
Reverts back to the to_s dump behavior in :compat mode to instead use an optimized dump that includes the classname and attributes so that the object can be re-created on load. The format is the same as the json gem but does not use the ruby methods for encoding.
The classes supported for optimization are: Array, BigDecimal, Complex, Date, DateTime, Exception, Hash, Integer, OpenStruct, Range, Rational, Regexp, Struct, and Time. Providing no classes will result in all those classes being reverted from the optimized mode.
-
args [Class] zero or more classes to optimize.
1439 |
# File 'ext/oj/oj.c', line 1439
extern VALUE oj_remove_to_json(int argc, VALUE *argv, VALUE self);
|
.safe_load(doc) ⇒ Object
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.
-
doc [String_|IO] JSON String or IO to load.
Returns [Hash|Array|String|Fixnum|Bignum|BigDecimal|nil|True|False]
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 |
# File 'ext/oj/oj.c', line 1007
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_parse(handler, io) ⇒ Object
Parses an IO stream or file containing a JSON document. Raises an exception if the JSON is malformed. This is a callback parser that calls the methods in the handler if they exist. A sample is the Oj::Saj class which can be used as a base class for the handler.
-
handler [Oj::Saj] responds to Oj::Saj methods
-
io [IO|String] IO Object to read from
.sc_parse(handler, io) ⇒ Object
Parses an IO stream or file containing a JSON document. Raises an exception if the JSON is malformed. This is a callback parser (Simple Callback Parser) that calls the methods in the handler if they exist. A sample is the Oj::ScHandler class which can be used as a base class for the handler. This callback parser is slightly more efficient than the Saj callback parser and requires less argument checking.
-
handler [Oj::ScHandler_] responds to Oj::ScHandler methods
-
io [IO_|String] IO Object to read from
.strict_load(json, options) { ... } ⇒ Object
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 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. The block can take up to 3 arguments, the parsed object, the position in the string or stream of the start of the JSON for that object, and the length of the JSON for that object plus trailing whitespace.
-
json [String|IO] JSON String or an Object that responds to read().
-
options [Hash] load options (same as default_options).
-
obj [Hash|Array|String|Fixnum|Float|Boolean|nil] parsed object.
-
start [_optional, Integer] start position of parsed JSON for obj.
-
len [_optional, Integer] length of parsed JSON for obj.
Returns [Hash|Array|String|Fixnum|Float|Boolean|nil]
1307 |
# File 'ext/oj/oj.c', line 1307
extern VALUE oj_strict_parse(int argc, VALUE *argv, VALUE self);
|
.to_file(file_path, obj, options = {}) ⇒ Object
Dumps an Object to the specified file.
-
file [String] _path file path to write the JSON document to
-
obj [Object] Object to serialize as an JSON document String
-
options [Hash] formating options
-
:indent [Fixnum] format expected
-
:circular [Boolean] allow circular references, default: false
-
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 |
# File 'ext/oj/oj.c', line 1159
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_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 [boolean] It true nesting is limited to 100. The option to detect circular references is available but is not compatible with the json gem., default is false
-
: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.
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 |
# File 'ext/oj/oj.c', line 1113
static VALUE
to_json(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).");
}
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;
out.buf = buf;
out.end = buf + sizeof(buf) - 10;
out.allocated = false;
out.omit_nil = copts.dump_opts.omit_nil;
// 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_str_new2(out.buf);
rstr = oj_encode(rstr);
if (out.allocated) {
xfree(out.buf);
}
return rstr;
}
|
.to_stream(io, obj, options = {}) ⇒ Object
Dumps an Object to the specified IO stream.
-
io [IO] IO stream to write the JSON document to
-
obj [Object] Object to serialize as an JSON document String
-
options [Hash] formating options
-
:indent [Fixnum] format expected
-
:circular [Boolean] allow circular references, default: false
-
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 |
# File 'ext/oj/oj.c', line 1182
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;
}
|
.wab_load(json, options) { ... } ⇒ Object
Parses a JSON document String into an Hash, Array, String, Fixnum, Float, true, false, or nil. It parses using a mode that is :wab 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 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. The block can take up to 3 arguments, the parsed object, the position in the string or stream of the start of the JSON for that object, and the length of the JSON for that object plus trailing whitespace.
-
json [String|IO] JSON String or an Object that responds to read().
-
options [Hash] load options (same as default_options).
-
obj [Hash|Array|String|Fixnum|Float|Boolean|nil] parsed object.
-
start [_optional, Integer] start position of parsed JSON for obj.
-
len [_optional, Integer] length of parsed JSON for obj.
Returns [Hash|Array|String|Fixnum|Float|Boolean|nil]
1406 |
# File 'ext/oj/oj.c', line 1406
extern VALUE oj_wab_parse(int argc, VALUE *argv, VALUE self);
|