Practical technical guides / AI engineering

Parse Streamed Model JSON Without Acting on Fields That Are Still Arriving

A streamed amount of 12 may become 125. Track which top-level JSON fields are complete, render previews only, and act on the whole object after the stream ends.

By Sandeep Belgavi · Published 2026-11-22

A streamed amount of 12 may become 125. Track which top-level JSON fields are complete, render previews only, and act on the whole object after the stream ends.

A preview that becomes an action

Streaming a model's structured output makes an interface feel fast. A help-desk tool at the fictional Belgavi's Book Store shows the agent's proposed action while it is still being generated: the case number appears, then the action, then the amount. The display code does the obvious thing with each partial buffer: close any open string, close any open brackets, parse, and render whatever fields exist.

Then someone wires the same partial object into an approval button, or a tool call, or an automatic check that starts as soon as action and amount are present. At that point the preview is no longer harmless. A partial buffer that ends with "amount": 12 parses to the number 12. The next chunk may be 5, and the real amount is 125.

This guide separates two things a streamed JSON object can tell you: what it currently looks like, and which of its fields are finished. Interfaces can use the first. Decisions must use only the second, or wait for the whole object.

Where streamed JSON comes from

Model APIs stream structured output in several ways. Anthropic's Messages API, for example, streams tool-use input as input_json_delta events whose partial_json field carries a fragment of the JSON string; its streaming documentation says the deltas are partial JSON strings, the final tool_use.input is always an object, and you can accumulate the deltas and parse once the content block stops. The same documentation says that, by default, the API buffers each key and value until it is complete and then emits them, possibly as several deltas. Other providers stream structured text with no such buffering. Your parser should not depend on how a particular provider chunks its output, because chunk boundaries are a transport detail and can fall anywhere.

When is a JSON value finished

The JSON grammar in RFC 8259 makes the answer precise for each value type:

  • A string is finished at its closing quotation mark. An escaped quote inside it does not end it.
  • An object or array is finished at the bracket that matches its opening bracket, which you can only find by tracking strings, because a bracket inside a string does not count.
  • A number has no terminator of its own. 12 is a valid number and so is 125; the number is finished only when the next character is a delimiter such as a comma, a closing brace or whitespace.
  • The literals true, false and null are the same: tru is not yet anything, and true is not certainly finished until a delimiter follows, although no valid continuation exists.

A top-level field of the object is complete when its value is complete. That is the only property a decision needs.

def end_of_value(buf, j):
    if buf[j] == '"':
        return end_of_string(buf, j)
    if buf[j] in '{[':
        return matching_bracket(buf, j)      # skips over strings
    k = j
    while k < len(buf) and buf[k] not in ',}' + ' \t\r\n':
        k += 1
    return k if k < len(buf) else None      # no delimiter yet: may still grow

The worked stream

The companion example feeds five chunks of a refund proposal for CASE-4201 and, after each, prints both the naive preview and the set of complete fields:

  1. After {"case_id": "CASE-4201", "action": "ref the preview shows action: "ref". Complete fields: only case_id.
  2. After und", "amount": 12 the preview shows action: "refund", amount: 12. Complete fields: case_id and action. The amount is not reported, because no delimiter has arrived.
  3. After 5, "items": [{"sku": "BK-7" the preview shows amount: 125 and an items list with one object. Complete fields now include amount: 125, but not items, because the object inside the array is still open and could gain a quantity.
  4. After }], "note": "Damaged cov the preview shows a truncated note. Complete fields include items.
  5. After er"} both agree, and the complete fields equal a full parse of the joined chunks.

Two of the naive preview's values were wrong at some point: an action that was a prefix of the real one, and an amount that was a prefix of the real number. A third, the items list, looked complete while its last object was still open. None of these would raise an error in the preview code.

Three rules for consumers

  1. Rendering may use the preview, clearly marked as in progress. A greyed amount that changes from 12 to 125 is acceptable on a screen.
  2. A field-level decision may use only complete fields. Prefetching the order for case_id as soon as it completes is safe: the value cannot change.
  3. An action that depends on the whole object waits for the end of the stream and a successful full parse, then validates against the schema. Field completeness says nothing about fields that have not arrived yet, so a proposal that is "complete enough" does not exist.

The third rule matters for agents because tool arguments often have a field that changes the meaning of the others. A dry_run field at the end of the object, or a currency field after the amount, must be present before anything runs.

Failure modes

  • Escapes: a scanner that ends strings at any quote breaks on \". Test strings containing escaped quotes and backslashes.
  • Unicode escapes split across chunks: é can arrive as \u00 and e9. Track the escape state across chunk boundaries, or only scan the accumulated buffer, as the example does.
  • Duplicate keys: RFC 8259 says names within an object should be unique and leaves behavior with duplicates unpredictable. A streamed object with amount twice should be rejected, not resolved by whichever parser you happen to use.
  • Truncated streams: a connection that drops after chunk three leaves a preview that looks plausible. Treat a missing end of stream as a failure, never as the final answer.
  • Model-side truncation: a response stopped by an output token limit is syntactically incomplete. Check the stop reason before parsing, and never repair the JSON and act on it.

Testing every chunk boundary

Chunk boundaries in production are not under your control, so a test that uses the five boundaries above proves little. Generate the boundaries instead. Take the complete text of a fixture, split it at every position into two chunks, and check two properties after each first chunk: every field the scanner reports complete has the same value it has in the full parse, and no field is reported that the full parse does not contain. Then repeat with three chunks at random positions under a fixed seed.

full = ''.join(CHUNKS)
expected = json.loads(full)
for cut in range(1, len(full)):
    seen = complete_fields(full[:cut])
    for key, value in seen.items():
        assert expected[key] == value, (cut, key, value)

For the 112-character refund fixture this is 111 cases, and it is the test that catches a number reported complete one character too early or a string ended at an escaped quote. The same harness checks any third-party partial parser you adopt: wrap its output in the same assertion and see whether it ever reports a value that later changes.

Is a custom scanner necessary

Usually not. Several JSON libraries offer incremental or partial parsing, and some provider SDKs expose parsed partial input through streaming helpers. The point of writing the small scanner here is to make the completeness rule explicit and testable, so that whichever library you use, you can check it against the cases above: a growing number, a growing literal, an open nested object and an escaped quote. If a library's partial result does not tell you which fields are complete, do not use it for decisions.

If nothing reads the stream before it ends, none of this is needed. Many tool-calling integrations simply wait for the complete arguments, which is the safest default. Streaming structured output is worth the extra care only when a person is watching it arrive.

Verification

The seven tests in the companion example check the prefix action, that the amount 12 is never reported complete, that the open nested object is not complete, that the final complete fields equal a full parse, that an escaped quote inside a string is handled, that a literal waits for a delimiter while the naive preview cannot parse tru at all, and the every-position split described above. Run your own streamed outputs through the same checks.

Run the example yourself

The completeness scanner, the naive preview, the five chunks and seven tests, including every split position. Companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.

Primary references and authorship

Sources read 22 November 2026. Original explanation, measurements and synthetic examples by Sandeep Belgavi. Views are my own and do not represent any employer, past or present.

Related on this site: