How can I read a stream of JSON objects into browser

949 Views Asked by At

Given a node.js style object stream as the example below shows, how can this be read by an http request on a webpage and processed:

{"id":"one",   "value":"the first object"}
{"id":"two",   "value":"the second object"}
{"id":"three", "value":"the third object"}
1

There are 1 best solutions below

2
On

Progressively parsing an http request is something that oboe.js is good for. What you're looking to send seems like something called JSON Lines. Technically, oboe only supports receiving a single valid JSON object or array. But I found that you can get it to work for your data :)

oboe('/data.json')
  .node('{id value}', function(x) {
    console.log('object', x)
  })
  .node('!', function(x) {
    console.log('root', x)
  })

You can use oboe to a request to load the data (it uses a native XMLHttpRequest under the hood). Then you use node to add a listener for any object that has both an id property and a values property, or for any root level object with !. Note that you do not have to use both.

You can view a working example here and the source code here.

Gotcha: One thing worth being aware of if you try to use oboe's done function is that it will trigger multiple times, once for each object. That's because each will be parsed as a full valid object.