ndjson-stream
ndjson-stream
offers a variety of NDJSON-parsers which accept data in chunks and process these chunks before reading
further, thus enabling a streaming-style use.
The parser accepts a variety of inputs which represent byte slices, e.g. Vec<u8>
or &str
.
ndjson-stream
uses the serde_json crate to parse individual lines.
High-level example
As an example, we will look at the iterator interface.
The most basic form can be instantiated with from_iter
.
We have to provide an iterator over data blocks, and obtain an iterator over parsed NDJSON-records.
Actually, the exact return type is a Result
which may contain a JSON-error in case a line is not valid JSON or does
not match the schema of the output type.
The example below demonstrates both the happy-path and parsing errors.
use Deserialize;
let data_blocks = vec!;
let mut ndjson_iter = ;
assert_eq!;
assert!;
assert_eq!;
assert!;
Configuration
There are several configuration options available to control how the parser behaves in certain situations.
In the example below, we construct an NDJSON-iterator which ignores blank lines. That is, it does not produce an output record for any line which consists only of whitespace rather than attempting to parse it and raising a JSON-error.
use ;
use Deserialize;
let data_blocks = vec!;
let config = default.with_empty_line_handling;
let mut ndjson_iter = ;
assert_eq!;
assert_eq!;
assert!;
Fallibility
In addition to the ordinary interfaces, there is a fallible counterpart for each one.
"Fallible" in this context refers to the input data source - in the examples above the iterator of data_blocks
.
Fallible parsers accept as input a data source which returns Result
s with some error type and forward potential read
errors to the user.
In the example below, we use a fallible iterator.
use FallibleNdjsonError;
use Deserialize;
let data_blocks = vec!;
let mut ndjson_iter = ;
assert_eq!;
assert!;
assert!;
assert!;
For further information on how to use the ndjson-stream
crate, view the crate documentation.