I've been scratching my head for days to solve this problem. I want to change value of some key from a relatively big JSON string streamed from the HTTP request, and then stream it to the client. Pretend this is a big JSON:
{
"name":"George",
"country": {
"home": "United States",
"current": "Canada"
}
}
And I want output like this by changing name.country.current
{
"name":"George",
"country": {
"home": "United States",
"current": "Indonesia"
}
}
The transformation is done within a restify handler:
let proxyHandler = function(req, res, next) {
let proxyReq = http.request(opt, r => {
r.on('data', data => {
// transform here and send the data using response.write();
// and close the response object
// when the parsing ends
});
proxyReq.end();
next();
}
I cannot use JSON.parse
because the size of the JSON is big, so I'd need to stream/parse/transform it as it arrives. Is there any library out there that able to do so?
I've tried using stream-json, however it's very slow when I need to combine the Transform stream. When I initiate a huge number of requests it just crawls and then timed out.
Because the client is not sent a Content-Length
header, the server need to close the stream.
UPDATE:
I understand that there's a streaming JSON parser. However what I need is not only a parser, but also emitter. The process would be
JSON -> Parse (event based) -> Transform parse event -> Emit the transformed JSON. All need to be done in NodeJS stream
.
As I've mentioned above, I've used stream-json, I'v written my stack-based emitter but it was slow and created backpressure when a lot of requests come in. What I ask if there's any node library out there that able to process in one go. Ideally, the library can be executed like below:
// JSONTransform is a hypotetical library class
result
.pipe(new JSONTransform('name.country.home', (val) => 'Indonesia')
.pipe(response)