API Reference
This section provides detailed documentation for the zzson
Rust library. The API is designed to be intuitive and idiomatic for Rust developers.
zzson::parse
pub fn parse(input: &str) -> Result<Value, Error>
Parses a JSON-like string into a zzson::Value
enum using default parser options. This is the primary entry point for using the library.
input
: The string slice containing the JSON-like data to parse.- Returns:
Ok(Value)
: If parsing is successful, returns aValue
enum representing the parsed data.Err(Error)
: If an error occurs during parsing, returns anError
detailing the issue.
zzson::parse_with_options
pub fn parse_with_options(input: &str, options: ParserOptions) -> Result<Value, Error>
Parses a JSON-like string into a zzson::Value
enum with custom parser options. This allows fine-grained control over which forgiving features are enabled.
input
: The string slice containing the JSON-like data to parse.options
: AParserOptions
struct configuring the parser’s behavior.- Returns:
Ok(Value)
: If parsing is successful, returns aValue
enum representing the parsed data.Err(Error)
: If an error occurs during parsing, returns anError
detailing the issue.
zzson::ParserOptions
This struct defines the configurable options for the zzson
parser.
pub struct ParserOptions {
pub allow_comments: bool,
pub allow_trailing_commas: bool,
pub allow_unquoted_keys: bool,
pub allow_single_quotes: bool,
pub implicit_top_level: bool,
pub newline_as_comma: bool,
pub max_depth: usize,
}
allow_comments
: Iftrue
, allows single-line (//
,#
) and multi-line (/* */
) comments. Default:true
.allow_trailing_commas
: Iftrue
, allows trailing commas in arrays and objects. Default:true
.allow_unquoted_keys
: Iftrue
, allows object keys without quotes (e.g.,key: "value"
). Default:true
.allow_single_quotes
: Iftrue
, allows strings to be enclosed in single quotes ('
). Default:true
.implicit_top_level
: Iftrue
, attempts to parse input not wrapped in{}
or[]
as an implicit top-level object or array. Default:true
.newline_as_comma
: Iftrue
, treats newlines as comma separators in arrays and objects. Default:true
.max_depth
: Maximum recursion depth for nested structures to prevent stack overflow. Default:128
.
ParserOptions
implements Default
, so you can create a default instance and then modify specific fields:
use zzson::ParserOptions;
let mut options = ParserOptions::default();
options.allow_comments = false; // Disable comments
options.max_depth = 64; // Set a custom max depth
zzson::Value
Enum
This enum represents the different types of JSON values that zzson
can parse.
pub enum Value {
Null,
Bool(bool),
Number(Number),
String(String),
Array(Vec<Value>),
Object(HashMap<String, Value>),
}
Null
: Represents a JSONnull
value.Bool(bool)
: Represents a JSON boolean (true
orfalse
).Number(Number)
: Represents a JSON numeric value. Seezzson::Number
for details.String(String)
: Represents a JSON string.Array(Vec<Value>)
: Represents a JSON array, a vector ofValue
enums.Object(HashMap<String, Value>)
: Represents a JSON object, a hash map of string keys toValue
enums.
Value
Helper Methods
The Value
enum provides several helper methods for type checking and value extraction:
is_null() -> bool
is_bool() -> bool
is_number() -> bool
is_string() -> bool
is_array() -> bool
is_object() -> bool
as_bool() -> Option<bool>
as_i64() -> Option<i64>
: ReturnsNone
if the number cannot be represented asi64
.as_f64() -> Option<f64>
as_str() -> Option<&str>
as_array() -> Option<&Vec<Value>>
as_object() -> Option<&HashMap<String, Value>>
zzson::Number
Enum
This enum represents a JSON number, which can be either an integer or a floating-point number.
pub enum Number {
Integer(i64),
Float(f64),
}
Integer(i64)
: An integer value that fits in ani64
.Float(f64)
: A floating-point value.
zzson::Error
Enum
This enum defines the types of errors that can occur during parsing.
pub enum Error {
UnexpectedChar(char, usize),
UnexpectedEof(usize),
InvalidNumber(usize),
InvalidEscape(usize),
InvalidUnicode(usize),
UnterminatedString(usize),
TrailingComma(usize),
Expected {
expected: String,
found: String,
position: usize,
},
DepthLimitExceeded(usize),
Custom(String),
}
UnexpectedChar(char, usize)
: Encountered an unexpected character during parsing at a given position.UnexpectedEof(usize)
: Reached the end of the input unexpectedly at a given position.InvalidNumber(usize)
: An invalid number format was encountered at a given position.InvalidEscape(usize)
: An invalid escape sequence was found in a string at a given position.InvalidUnicode(usize)
: An invalid Unicode escape sequence was found at a given position.UnterminatedString(usize)
: A string literal was not properly terminated, starting at a given position.TrailingComma(usize)
: A trailing comma was found where not allowed (though typically allowed byzzson
’s forgiving nature, this error might occur in strict modes or specific contexts) at a given position.Expected { expected: String, found: String, position: usize }
: The parser expected a specific token or value but found something else at a given position.DepthLimitExceeded(usize)
: The maximum recursion depth was exceeded while parsing nested structures at a given position.Custom(String)
: A custom error with a descriptive message.
Error
Helper Methods
position() -> Option<usize>
: Returns the character position in the input where the error occurred, if available.
Serde Integration
zzson
provides optional integration with the serde
serialization framework. When the serde
feature is enabled in your Cargo.toml
, zzson::Value
and zzson::Number
implement the Serialize
and Deserialize
traits. This allows easy conversion between zzson::Value
and other data formats supported by Serde (e.g., serde_json::Value
).
To enable this feature, add serde
to your zzson
dependency in Cargo.toml
:
[dependencies]
zzson = { version = "1.1.0", features = ["serde"] }
Example:
use zzson::{parse, Value};
use serde_json; // Requires `serde_json` crate
fn main() {
let json_str = r#"{ "name": "Alice", "age": 30 }"#;
let zzson_value: Value = parse(json_str).unwrap();
// Convert zzson::Value to serde_json::Value
let serde_value: serde_json::Value = serde_json::to_value(zzson_value).unwrap();
println!("Converted to serde_json::Value: {}", serde_value);
// Convert serde_json::Value back to zzson::Value
let new_zzson_value: Value = serde_json::from_value(serde_value).unwrap();
println!("Converted back to zzson::Value: {:?}", new_zzson_value);
}
WebAssembly (WASM) Bindings
zzson
offers WebAssembly bindings, allowing it to be used directly in JavaScript environments (e.g., web browsers, Node.js). This is enabled via the wasm
feature.
To enable this feature, add wasm
to your zzson
dependency in Cargo.toml
:
[dependencies]
zzson = { version = "1.1.0", features = ["wasm"] }
For detailed documentation on the WebAssembly API, including JavaScript examples, please refer to the WASM API Reference.