Build a streaming JSON parser: path selectors, items emitted as they complete and exact error positions
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
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 2
- code listings
- 7
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1You cannot wait for the whole text, so the parser must be able to stop after any character and continue with the next chunk. Keep all state in variables: a stack of open containers, the current path, and the token being read (string, number or literal) with its progress.
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.