Skip to content

Function: parsePartialJson()

@providerprotocol/ai


@providerprotocol/ai / utils / parsePartialJson

parsePartialJson<T>(json): PartialParseResult<T>

Defined in: src/utils/partial-json.ts:217

Parses potentially incomplete JSON, returning as much as can be extracted.

Handles common incomplete states during streaming:

  • Incomplete strings: {"name":"Jo → {name: "Jo"}
  • Incomplete objects: {"a":1,"b": → {a: 1}
  • Incomplete arrays: [1,2, → [1, 2]
  • Incomplete numbers, booleans, null literals
  • Nested structures with partial completion
  • Unicode escape sequences

T = unknown

The expected type of the parsed value

string

The potentially incomplete JSON string

PartialParseResult<T>

A PartialParseResult with the parsed value and completion status

// Complete JSON
parsePartialJson('{"name":"John"}');
// => { value: { name: "John" }, isComplete: true }
// Incomplete object
parsePartialJson('{"user":{"firstName":"Jo');
// => { value: { user: { firstName: "Jo" } }, isComplete: false }
// Incomplete array
parsePartialJson('[1, 2, 3');
// => { value: [1, 2, 3], isComplete: false }