Build a streaming JSON parser: path selectors, items emitted as they complete and exact error positions

hardAbout 70 minutesUpdated CodingProjavascriptparsingjsonstreamingstate-machine
Not solved

Share this question

Problem

An API returns a 50 MB JSON document like { "items": [ ... 100,000 objects ... ], "meta": { ... } }. With await res.json() the user sees nothing until the last byte arrives, and the whole tree sits in memory. Streaming parsers such as Oboe.js (built on the clarinet SAX parser) read the text as it arrives and hand over each matching item as soon as it is complete, so the list can render the first rows while the rest downloads.

const parser = createJsonStream({
  select: ["$.items[*]"],
  onValue: (item, path) => appendRow(item), // path is ["items", 0], ["items", 1], ...
});
for await (const chunk of response.body.pipeThrough(new TextDecoderStream())) parser.write(chunk);
parser.end();

Ref. UR-1447 · © UIRound · uiround.com/questions/build-a-streaming-json-parser-path-selectors-items-emitted-as-they-complete-and-exact-error-positions

Stuck? Take a hint

Try it in the editor

Run your code as often as you like. Submitting it to the full test suite is part of Pro.

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment