JSONStream is a node.js package that allows for streaming of JSON.parse
and stringify
. It allows the parsing and stringifying of JSON data in a way that's memory-efficient and fast, making it ideal for use when dealing with particularly large JSON objects.
To use JSONStream, you first need to install it by running npm install JSONStream
in the command line. Once you've installed the package, you can require it in your node.js project.
Here's an example of its usage:
var request = require('request')
var JSONStream = require('JSONStream')
var es = require('event-stream')
request({url: 'http://isaacs.couchone.com/registry/_all_docs'})
.pipe(JSONStream.parse('rows.*'))
.pipe(es.mapSync(function (data) {
console.error(data)
return data
}))
In this code snippet, JSONStream is used to parse data from a URL 'http://isaacs.couchone.com/registry/_all_docs'. Then it looks for JSON objects that match the 'rows.*' pattern and pipes them through an event-stream which logs the data to the console. To match a child at any depth, you can use the ..
operator, which is the recursive descent operator.
You can also use a function to map or filter the JSON output. The map function would be passed the value at that node of the pattern and if the map returns non-nullish, that value will be emitted in the stream.
Here is an another example with more depth:
var stream = JSONStream.parse(['rows', true, 'doc', {emitKey: true}]) //rows, ANYTHING, doc, items in docs with keys
stream.on('data', function(data) {
console.log('key:', data.key);
console.log('value:', data.value);
});
For JSONStream documentations, one can refer to the README available at the package's GitHub repository here. The README file offers extensive guidance on how to use the module, including various examples and different uses of methods. You can also visit NPM's webpage for JSONStream here for more information and usage examples.