A streaming SAX-style JSON parser.
This is a fork of jsonparse
.
$ npm install json-event-parser
or
$ yarn add json-event-parser
This package also works out-of-the-box in browsers via tools such as webpack and browserify.
Example:
import {JsonEventParser} from 'json-event-parser';
import {Readable} from "stream";
Readable.from(['{"test": "fo', 'o"}'])
.pipe(new JsonEventParser())
.on("end", () => console.log('Parsing done!'))
.on("error", error => console.error(error))
.on("data", event => console.log(`Event of type ${event.type}`));
The event fields are:
type
: the event type. Might be"value"
(a plain value i.e. a string, a number, a boolean or null),"open-array"
and"close-array"
to mark that an array is opened and close, or"open-object"
and"close-object"
to mark the same thing with objects.value
: used on the"value"
type to store the value itself.key
: used on the"value"
,"open-array"
and"open-object"
to store the key in the parent object or the position in the parent array.
It is also possible to evaluate queries against a given JSON stream:
import {JsonEventParser, JsonStreamPathTransformer} from 'json-event-parser';
import {Readable} from "stream";
Readable.from(['{"test": "fo', 'o"}'])
.pipe(new JsonEventParser())
.pipe(new JsonStreamPathTransformer([{id: 'test', query: ['test']}]))
.on("end", () => console.log('Parsing done!'))
.on("error", error => console.error(error))
.on("data", result => console.log(`Matched ${result.value}`));
This code is released under the MIT license.