Skip to main content

rust_json_parser/
lib.rs

1//! # Rust JSON Parser
2//!
3//! A JSON parser written in Rust for learning and demonstrating
4//! parsing techniques, error handling, and Python integration.
5//!
6//! ## Try My Rust Parser
7//!
8//! [Launch the JSON Playground](https://jpyle40.github.io/barkleysparser/playground.html)
9//!
10//! Run my Rust JSON parser directly in your browser using WebAssembly.
11//!
12//! ## Features
13//!
14//! - Tokenizes JSON input into individual tokens.
15//! - Parses JSON into structured `JsonValue` types.
16//! - Supports objects, arrays, strings, numbers, booleans, and null.
17//! - Provides descriptive errors for invalid JSON input.
18//! - Supports Python integration through optional PyO3 bindings.
19//!
20//! ## Example
21//!
22//! ```
23//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
24//! use rust_json_parser::{parse_json, JsonValue};
25//!
26//! let result = parse_json(r#"{"name": "server01"}"#)?;
27//!
28//! assert!(matches!(result, JsonValue::Object(_)));
29//! # Ok(())
30//! # }
31//! ```
32//!
33//! ## Python Integration
34//!
35//! Enable the `python` feature to build Python bindings using PyO3.
36
37mod error;
38mod parser;
39mod tokenizer;
40mod value;
41
42#[cfg(feature = "python")]
43mod python_bindings;
44#[cfg(feature = "wasm-bindgen")]
45mod wasm_bindings;
46
47pub use error::JsonError;
48pub use parser::parse_json;
49pub use tokenizer::{Token, Tokenizer};
50pub use value::JsonValue;
51
52pub type Result<T> = std::result::Result<T, JsonError>;
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57    #[test]
58    fn test_integration() -> Result<()> {
59        //Test the full parsing pipline
60        assert_eq!(parse_json("42")?, JsonValue::Number(42.0));
61        assert_eq!(parse_json("true")?, JsonValue::Boolean(true));
62        assert_eq!(parse_json("null")?, JsonValue::Null);
63        assert_eq!(
64            parse_json(r#""hello""#)?,
65            JsonValue::String("hello".to_string())
66        );
67        Ok(())
68    }
69    #[test]
70    fn test_error_propagation() {
71        let result = parse_json("@invalid@");
72        assert!(result.is_err());
73
74        match result {
75            Err(JsonError::UnexpectedToken {
76                expected,
77                found,
78                position,
79            }) => {
80                assert_eq!(expected, "valid JSON token");
81                assert_eq!(found, "@");
82                assert_eq!(position, 0);
83            }
84
85            _ => panic!("Expected UnexpectedToken error"),
86        }
87    }
88}