Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
JSON::ResumableParser.new
static VALUE cResumableParser_initialize(int argc, VALUE *argv, VALUE self)
{
rb_check_frozen(self);
VALUE opts = Qfalse;
rb_scan_args_kw(RB_SCAN_ARGS_LAST_HASH_KEYWORDS, argc, argv, "0:", &opts);
JSON_ResumableParser *parser = cResumableParser_get(self);
opts = argc > 0 ? argv[0] : Qnil;
parser_config_init(&parser->config, opts, self, true);
return self;
}
Creates a new JSON::ResumableParser instance.
Argument opts, if given, contains a Hash of options for the parsing. See Parsing Options.
A ResumableParser is able to parse partial documents and resume parsing later when more of the document is provided:
parser = JSON::ResumableParser.new parser << '{"user": "george", "role": "ad' parser.parse # => false parser.eos? # => true parser.partial_value # => { "user" => "george", "role" => nil } parser.rest # => '"ad' parser << 'min" }[1, 2, 3]' parser.parse # => true parser.value # => { "user" => "george", "role" => "admin" } parser.parse # => true parser.value # => [1, 2, 3]
Limitations
While ResumableParser is able to parse streams of documents without any explicit separators between them, it is highly recommended to separate documents by either spaces or newlines, as otherwise the JSON syntax for numbers may be ambiguous. When parsing a number, ResumableParser will not consider the number complete until something follows:
parser << '123' parser.parse # => false parser << ' ' parser.parse # => true parser.value # => 123
Security
An incomplete document is buffered in full and there is no size limit, so when reading from an untrusted source the caller is responsible for bounding how much data is fed. For example:
loop do if parser.parsed_bytes > DOCUMENT_MAX_SIZE raise "document too large" end parser << read_chunk while parser.parse process(parser.value) end end