Method: Oj.load
- Defined in:
- ext/oj/oj.c
.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]
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 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 |
# File 'ext/oj/oj.c', line 737
static VALUE
load(int argc, VALUE *argv, VALUE self) {
Mode mode = oj_default_options.mode;
if (1 > argc) {
rb_raise(rb_eArgError, "Wrong number of arguments to load().");
}
if (2 <= argc) {
VALUE ropts = argv[1];
VALUE v;
Check_Type(ropts, T_HASH);
if (Qnil != (v = rb_hash_lookup(ropts, mode_sym))) {
if (object_sym == v) {
mode = ObjectMode;
} else if (strict_sym == v) {
mode = StrictMode;
} else if (compat_sym == v || 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 {
rb_raise(rb_eArgError, ":mode must be :object, :strict, :compat, :null, :custom, or :rails.");
}
}
}
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 ObjectMode:
default:
break;
}
return oj_object_parse(argc, argv, self);
}
|