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/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 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.
-
:strict mode will only allow the 7 basic JSON types to be serialized. Any other Object will raise and Exception.
-
:null mode replaces any Object that is not one of the JSON 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 mode is is the compatible with other systems. It will serialize any Object but will check to see if the Object implements a to_hash() or to_json() method. If either exists that method is used for serializing the Object. The to_hash() is more flexible and produces more consistent output so it has a preference over the to_json() method. If neither the to_json() or to_hash() methods exist then the Oj internal Object variable encoding is used.
Defined Under Namespace
Classes: ActiveSupportHelper, Bag, CStack, DepthError, Doc, Error, LoadError, MimicError, ParseError, Saj, ScHandler, StreamWriter, StringWriter
Constant Summary collapse
- VERSION =
Current version of the module.
'2.11.2'
Class Method Summary collapse
-
.compat_load(json, options) ⇒ Object, ...
Parses a JSON document String into an Object, Hash, Array, String, Fixnum, Float, true, false, or nil.
-
.default_options ⇒ Hash
Returns the default load and dump options as a Hash.
-
.default_options=(opts) ⇒ nil
Sets the default options for load and dump.
-
.dump(obj, options) ⇒ Object
Dumps an Object (obj) to a 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 ⇒ Object
call-seq: load_file(path, options) => Object, Hash, Array, String, Fixnum, Float, true, false, or nil.
-
.mimic_JSON ⇒ Object
call-seq: mimic_JSON() => Module.
- .mimic_loaded(mimic_paths = []) ⇒ Object
-
.object_load(json, options) ⇒ Object, ...
Parses a JSON document String into an Object, Hash, Array, String, Fixnum, Float, true, false, or nil.
-
.register_odd(clas, create_object, create_method, *members) ⇒ Object
Registers a class as special.
-
.safe_load(doc) ⇒ Hash|Array|String|Fixnum|Bignum|BigDecimal|nil|True|False
Loads a JSON document in strict mode with :auto_define and :symbol_keys turned off.
- .saj_parse ⇒ Object
- .sc_parse ⇒ Object
-
.strict_load(json, options) ⇒ Hash, ...
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_stream(io, obj, options) ⇒ Object
Dumps an Object to the specified IO stream.
Class Method Details
.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.
.default_options ⇒ Hash
Returns the default load and dump options as a Hash. The options are
-
indent: [Fixnum] number of spaces to indent each element in an JSON document, zero is no newline between JSON elements, negative indicates no newline between top level JSON elements in a stream
-
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|:xmlschema|:ruby] time format when dumping in :compat 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
-
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)
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 |
# File 'ext/oj/oj.c', line 206 static VALUE get_def_opts(VALUE self) { VALUE opts = rb_hash_new(); rb_hash_aset(opts, indent_sym, INT2FIX(.indent)); rb_hash_aset(opts, sec_prec_sym, INT2FIX(.sec_prec)); rb_hash_aset(opts, circular_sym, (Yes == .circular) ? Qtrue : ((No == .circular) ? Qfalse : Qnil)); rb_hash_aset(opts, class_cache_sym, (Yes == .class_cache) ? Qtrue : ((No == .class_cache) ? Qfalse : Qnil)); rb_hash_aset(opts, auto_define_sym, (Yes == .auto_define) ? Qtrue : ((No == .auto_define) ? Qfalse : Qnil)); rb_hash_aset(opts, symbol_keys_sym, (Yes == .sym_key) ? Qtrue : ((No == .sym_key) ? Qfalse : Qnil)); rb_hash_aset(opts, bigdecimal_as_decimal_sym, (Yes == .bigdec_as_num) ? Qtrue : ((No == .bigdec_as_num) ? Qfalse : Qnil)); rb_hash_aset(opts, use_to_json_sym, (Yes == .to_json) ? Qtrue : ((No == .to_json) ? Qfalse : Qnil)); rb_hash_aset(opts, nilnil_sym, (Yes == .nilnil) ? Qtrue : ((No == .nilnil) ? Qfalse : Qnil)); rb_hash_aset(opts, allow_gc_sym, (Yes == .allow_gc) ? Qtrue : ((No == .allow_gc) ? Qfalse : Qnil)); rb_hash_aset(opts, quirks_mode_sym, (Yes == .quirks_mode) ? Qtrue : ((No == .quirks_mode) ? Qfalse : Qnil)); rb_hash_aset(opts, float_prec_sym, INT2FIX(.float_prec)); switch (.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 (.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 (.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 UnixTime: default: rb_hash_aset(opts, time_format_sym, unix_sym); break; } switch (.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 == .create_id) ? Qnil : rb_str_new2(.create_id)); return opts; } |
.default_options=(opts) ⇒ nil
Sets the default options for load and dump.
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 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 |
# File 'ext/oj/oj.c', line 289 static VALUE set_def_opts(VALUE self, VALUE opts) { struct _YesNoOpt ynos[] = { { circular_sym, &.circular }, { auto_define_sym, &.auto_define }, { symbol_keys_sym, &.sym_key }, { class_cache_sym, &.class_cache }, { bigdecimal_as_decimal_sym, &.bigdec_as_num }, { use_to_json_sym, &.to_json }, { nilnil_sym, &.nilnil }, { allow_gc_sym, &.allow_gc }, { quirks_mode_sym, &.quirks_mode }, { Qnil, 0 } }; YesNoOpt o; VALUE v; Check_Type(opts, T_HASH); v = rb_hash_aref(opts, indent_sym); if (Qnil != v) { Check_Type(v, T_FIXNUM); .indent = FIX2INT(v); } v = rb_hash_aref(opts, float_prec_sym); if (Qnil != v) { int n; Check_Type(v, T_FIXNUM); n = FIX2INT(v); if (0 >= n) { *.float_fmt = '\0'; .float_prec = 0; } else { if (20 < n) { n = 20; } sprintf(.float_fmt, "%%0.%dg", n); .float_prec = n; } } v = rb_hash_aref(opts, sec_prec_sym); if (Qnil != v) { int n; Check_Type(v, T_FIXNUM); n = FIX2INT(v); if (0 > n) { n = 0; } else if (9 < n) { n = 9; } .sec_prec = n; } v = rb_hash_lookup(opts, mode_sym); if (Qnil == v) { // ignore } else 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."); } v = rb_hash_lookup(opts, time_format_sym); if (Qnil == v) { // ignore } else if (unix_sym == v) { .time_format = UnixTime; } else if (xmlschema_sym == v) { .time_format = XmlTime; } else if (ruby_sym == v) { .time_format = RubyTime; } else { rb_raise(rb_eArgError, ":time_format must be :unix, :xmlschema, or :ruby."); } v = rb_hash_lookup(opts, escape_mode_sym); if (Qnil == v) { // ignore } else if (newline_sym == v) { .escape_mode = NLEsc; } else if (json_sym == v) { .escape_mode = JSONEsc; } else if (xss_safe_sym == v) { .escape_mode = XSSEsc; } else if (ascii_sym == v) { .escape_mode = ASCIIEsc; } else { rb_raise(rb_eArgError, ":escape_mode must be :newline, :json, :xss_safe, or :ascii."); } v = rb_hash_lookup(opts, bigdecimal_load_sym); if (Qnil == v) { // ignore } else if (bigdecimal_sym == v || Qtrue == v) { .bigdec_load = BigDec; } else if (float_sym == v) { .bigdec_load = FloatDec; } else if (auto_sym == v || Qfalse == v) { .bigdec_load = AutoDec; } else { rb_raise(rb_eArgError, ":bigdecimal_load must be :bigdecimal, :float, or :auto."); } if (Qtrue == rb_funcall(opts, rb_intern("has_key?"), 1, create_id_sym)) { if (0 != .create_id) { if (json_class != .create_id) { xfree((char*).create_id); } .create_id = 0; .create_id_len = 0; } v = rb_hash_lookup(opts, create_id_sym); if (Qnil != v) { size_t len = RSTRING_LEN(v) + 1; .create_id = ALLOC_N(char, len); strcpy((char*).create_id, StringValuePtr(v)); .create_id_len = len - 1; } } for (o = ynos; 0 != o->attr; o++) { if (Qtrue != rb_funcall(opts, rb_intern("has_key?"), 1, o->sym)) { continue; } if (Qnil != (v = rb_hash_lookup(opts, o->sym))) { if (Qtrue == v) { *o->attr = Yes; } else if (Qfalse == v) { *o->attr = No; } else { rb_raise(rb_eArgError, "%s must be true, false, or nil.", rb_id2name(SYM2ID(o->sym))); } } } // This is here only for backwards compatibility with the original Oj. v = rb_hash_lookup(opts, ascii_only_sym); if (Qtrue == v) { .escape_mode = ASCIIEsc; } else if (Qfalse == v) { .escape_mode = JSONEsc; } return Qnil; } |
.dump(obj, options) ⇒ Object
Dumps an Object (obj) to a string.
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 |
# File 'ext/oj/oj.c', line 858 static VALUE dump(int argc, VALUE *argv, VALUE self) { char buf[4096]; struct _Out out; struct _Options copts = ; VALUE rstr; if (2 == argc) { (argv[1], &copts); } out.buf = buf; out.end = buf + sizeof(buf) - 10; out.allocated = 0; 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; } |
.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.
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 |
# File 'ext/oj/oj.c', line 692 static VALUE load(int argc, VALUE *argv, VALUE self) { Mode mode = .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 != (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 ⇒ Object
call-seq: load_file(path, options) => Object, Hash, Array, String, Fixnum, Float, true, false, or nil
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.
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 |
# File 'ext/oj/oj.c', line 752 static VALUE load_file(int argc, VALUE *argv, VALUE self) { char *path; int fd; Mode mode = .mode; struct _ParseInfo pi; if (1 > argc) { rb_raise(rb_eArgError, "Wrong number of arguments to load()."); } Check_Type(*argv, T_STRING); pi. = ; pi.handler = Qnil; if (2 <= argc) { VALUE ropts = argv[1]; VALUE v; 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 ⇒ Object
call-seq: mimic_JSON() => Module
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.
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 |
# File 'ext/oj/oj.c', line 1818 static VALUE define_mimic_json(int argc, VALUE *argv, VALUE self) { VALUE ext; VALUE dummy; // 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"); } 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); } } dummy = rb_gv_get("$VERBOSE"); rb_gv_set("$VERBOSE", Qfalse); 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_create_id, 1); 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", dummy); array_nl_sym = ID2SYM(rb_intern("array_nl")); rb_gc_register_address(&array_nl_sym); create_additions_sym = ID2SYM(rb_intern("create_additions")); rb_gc_register_address(&create_additions_sym); object_nl_sym = ID2SYM(rb_intern("object_nl")); rb_gc_register_address(&object_nl_sym); space_before_sym = ID2SYM(rb_intern("space_before")); rb_gc_register_address(&space_before_sym); space_sym = ID2SYM(rb_intern("space")); rb_gc_register_address(&space_sym); symbolize_names_sym = ID2SYM(rb_intern("symbolize_names")); rb_gc_register_address(&symbolize_names_sym); if (rb_const_defined_at(mimic, rb_intern("ParserError"))) { rb_funcall(mimic, rb_intern("remove_const"), 1, ID2SYM(rb_intern("ParserError"))); } rb_define_const(mimic, "ParserError", oj_parse_error_class); if (!rb_const_defined_at(mimic, rb_intern("State"))) { rb_define_class_under(mimic, "State", rb_cObject); } = ; .to_json = Yes; return mimic; } |
.mimic_loaded(mimic_paths = []) ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 |
# File 'lib/oj/mimic.rb', line 4 def self.mimic_loaded(mimic_paths=[]) $LOAD_PATH.each do |d| next unless File.exist?(d) offset = d.size() + 1 Dir.glob(File.join(d, '**', '*.rb')).each do |file| next if file[offset..-1] !~ /^json[\/\\\.]{1}/ $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') 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.
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.
.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.
943 944 945 946 947 948 949 950 951 952 953 954 955 956 |
# File 'ext/oj/oj.c', line 943 static VALUE register_odd(int argc, VALUE *argv, VALUE self) { if (3 > argc) { rb_raise(rb_eArgError, "incorrect number of arguments."); } Check_Type(argv[0], T_CLASS); 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); return Qnil; } |
.safe_load(doc) ⇒ Hash|Array|String|Fixnum|Bignum|BigDecimal|nil|True|False
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.
813 814 815 816 817 818 819 820 821 822 823 824 825 826 |
# File 'ext/oj/oj.c', line 813 static VALUE safe_load(VALUE self, VALUE doc) { struct _ParseInfo pi; VALUE args[1]; pi. = ; pi..auto_define = No; pi..sym_key = No; pi..mode = StrictMode; oj_set_strict_callbacks(&pi); *args = doc; return oj_pi_parse(1, args, &pi, 0, 0, 1); } |
.saj_parse ⇒ Object
.sc_parse ⇒ Object
.strict_load(json, options) ⇒ Hash, ...
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.
.to_file(file_path, obj, options) ⇒ Object
Dumps an Object to the specified file.
893 894 895 896 897 898 899 900 901 902 903 904 |
# File 'ext/oj/oj.c', line 893 static VALUE to_file(int argc, VALUE *argv, VALUE self) { struct _Options copts = ; if (3 == argc) { (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) ⇒ Object
Dumps an Object to the specified IO stream.
915 916 917 918 919 920 921 922 923 924 925 |
# File 'ext/oj/oj.c', line 915 static VALUE to_stream(int argc, VALUE *argv, VALUE self) { struct _Options copts = ; if (3 == argc) { (argv[2], &copts); } oj_write_obj_to_stream(argv[1], *argv, &copts); return Qnil; } |