pub struct PartialJsonParser { /* private fields */ }Expand description
Incremental JSON parser that can handle partial/incomplete JSON.
Builds up a string token by token and attempts to parse at each step, returning the best partial result possible. This is designed for streaming LLM output where JSON arrives in small chunks and may be incomplete until the stream finishes.
§Strategy
- Accumulate tokens into an internal buffer.
- On each
push_and_parse, attempt to parse the buffer as complete JSON. - If that fails, try to repair the partial JSON by closing unclosed brackets/braces and truncating incomplete string values.
- If repair yields valid JSON, return it; otherwise return
PartialJsonError::Incomplete.
§Example
ⓘ
let mut parser = PartialJsonParser::new();
// Simulating token-by-token LLM output
let _ = parser.push_and_parse(r#"{"name":"#); // Incomplete
let v = parser.push_and_parse(r#""Alice","age":30}"#); // Ok({"name":"Alice","age":30})Implementations§
Source§impl PartialJsonParser
impl PartialJsonParser
Sourcepub fn push_and_parse(&mut self, token: &str) -> Result<Value, PartialJsonError>
pub fn push_and_parse(&mut self, token: &str) -> Result<Value, PartialJsonError>
Push a new token and attempt to parse the accumulated buffer.
Returns Ok(value) if the buffer (after optional repair) yields valid
JSON, or Err(PartialJsonError::Incomplete) if it does not yet form
any parseable JSON.
Sourcepub fn finalize(self) -> Result<Value, PartialJsonError>
pub fn finalize(self) -> Result<Value, PartialJsonError>
Get the final complete value.
Call this when the stream has ended. It first tries to parse the full buffer, then falls back to the repaired version.
Sourcepub fn is_in_string(&self) -> bool
pub fn is_in_string(&self) -> bool
Whether the parser is currently inside a JSON string.
Trait Implementations§
Auto Trait Implementations§
impl Freeze for PartialJsonParser
impl RefUnwindSafe for PartialJsonParser
impl Send for PartialJsonParser
impl Sync for PartialJsonParser
impl Unpin for PartialJsonParser
impl UnsafeUnpin for PartialJsonParser
impl UnwindSafe for PartialJsonParser
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more