Frame · dsa / ai-algorithms / 14-streaming-partial-json-parser.jsJavaScript
Streaming Partial JSON Parser for Tool-Call Arguments
Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.
Same file as in the repo · ~20s timeout
From file header (JSDoc)
Streaming Partial JSON Parser for Tool-Call Arguments
Problem: When an LLM streams a tool call, its JSON arguments arrive in
fragments such as `{"city": "Par`. UIs and agents want a best-effort object
at every step. Implement `parsePartialJSON(text)` that returns the value
described by the (possibly truncated) JSON prefix:
- Unclosed objects and arrays are closed implicitly.
- An unterminated string value is returned as the characters seen so far
(an incomplete escape at the end is dropped).
- An object key that is unterminated, or has no value yet, is omitted.
- A truncated number keeps its valid prefix (`12.` -> 12, `-` -> omitted).
- A truncated literal (`tr`, `nu`) is omitted.
- Empty or whitespace-only input returns undefined.
Complete JSON must parse exactly like `JSON.parse`. Malformed input (not a
prefix of valid JSON) throws a SyntaxError.
Constraints:
- input length <= 10^6; nesting depth <= 1000
Example:
'{"city": "Par' -> { city: "Par" }
'{"units": "metric", "days": [1, 2' -> { units: "metric", days: [1, 2] }
'{"verbose": tr' -> {}
Approach: A recursive-descent parser over the prefix where every routine
treats end-of-input as "stop and return what you have" rather than an
error. A MISSING sentinel signals "no usable value", which lets containers
drop the dangling key or element. Re-parsing the whole buffer on each chunk
costs O(n) per call (O(n) space for the result); incremental parsers avoid
the repeat work for very long arguments.
@param {string} text
@returns {unknown}