Skip to main content

Module syntax

Module syntax 

Source
Expand description

Parse the structural meaning of a stream of JSON text (syntactic analysis).

The key type in this module is Parser, a JSON syntax parser that wraps any lexical analyzer, i.e., any value implementing the lexical::Analyzer trait.

A Parser verifies, in a stream-oriented manner, that a JSON text is syntactically valid according to the JSON spec. It does not transform a JSON text into any kind of persistent in-memory data structure, abstract syntax tree, DOM, etc. Doing so would interfere with this crate’s focus on streaming, minimizing copies and allocations, and would be redundant given the multitude of crates that already perform that function.

§Example

Parse JSON text containing an array of numbers into a vector.

use bufjson::{lexical::{Token, fixed::FixedAnalyzer}, syntax::Parser};

fn parse_numbers(text: &str) -> Result<Vec<u32>, String> {
    let lexer = FixedAnalyzer::new(text.as_bytes());
    let mut parser = Parser::new(lexer);        // You can also do `lexer.into_parser()`

    let token = parser.next_meaningful();       // Skip whitespace, colons, and commas
    if token != Token::ArrBegin {
        return Err(format!("expected [ but got {token} at {}", *parser.pos()));
    }

    let mut numbers = Vec::new();

    loop {
        let token = parser.next_meaningful();   // Skip whitespace, colons, and commas
        match token {
            Token::Num => {
                match parser.content().literal().parse::<u32>() {
                    Ok(number) => numbers.push(number),
                    Err(err) => break Err(format!("{err}")),
                }
            },
            Token::ArrEnd => break Ok(numbers),
            Token::Err => break Err(format!("{}", parser.err())),
            _ => break Err(format!("expected number but got {token} at {}", *parser.pos())),
        }
    }
}

// Successful parses.
assert!(matches!(parse_numbers(" [ ] "), Ok(v) if v == vec![]));
assert!(matches!(parse_numbers("[1, 2, 3]"), Ok(v) if v == vec![1, 2, 3]));

// Syntax error caught by the parser.
assert!(matches!(parse_numbers("[}"), Err(err)
    if err == "syntax error: expected array element or ] but got } at line 1, column 2 (offset: 1)"));

Structs§

Context
State of a Parser.
Error
Parse error detected by Parser.
Parser
Parses JSON text at a syntax level.
StructIter
Iterator over the StructKind values that define the nesting level of a parser context.

Enums§

ErrorKind
Category of parsing error that can occur while parsing a JSON text.
Expect
Token or class of token the Parser expects to see next.
StructKind
Type of structured JSON value: Arr or Obj.