my_json_parser_proj/
lib.rs

1use pest::Parser;
2use pest_derive::Parser;
3use thiserror::Error;
4
5/// Custom error type for JSON parsing errors.
6#[derive(Debug, Error)]
7pub enum JsonParseError {
8    #[error("Invalid JSON structure")]
9    InvalidStructure,
10    #[error("Parsing error: {0}")]
11    ParsingError(String),
12}
13
14/// Define the Pest parser using the grammar in json.pest.
15#[derive(Parser)]
16#[grammar = "grammar/json.pest"]
17struct JsonParser;
18
19/// Validates if the input string is valid JSON according to the grammar.
20pub fn validate_json(input: &str) -> Result<(), JsonParseError> {
21    JsonParser::parse(Rule::json, input)
22        .map(|_| ())
23        .map_err(|e| JsonParseError::ParsingError(e.to_string()))
24}
25
26/// Parses JSON and identifies if it contains a specific object structure.
27pub fn parse_object(input: &str) -> Result<(), JsonParseError> {
28    let mut parsed = JsonParser::parse(Rule::object, input)
29        .map_err(|e| JsonParseError::ParsingError(e.to_string()))?;
30
31    if parsed.next().is_some() {
32        println!("There is at least one more item in the iterator.");
33    }
34
35    Ok(())
36}