jsonparser/lib.rs
1mod utils;
2
3use utils::{Lexer, Parser};
4pub use utils::{JSONValue, OrderedMap, Serialize};
5pub use utils::{JSONSchema, Validator, StringType, NumberType, BooleanType, ArrayType, ObjectType, NullType};
6
7/// A JSON parser that can parse a JSON input string to a JSONValue.
8///
9/// # Example
10///
11/// ```no_run
12/// use jsonparser::JSONParser;
13///
14/// let input = r#"
15/// {
16/// "name": "John Doe",
17/// "age": 30
18/// }
19/// "#;
20///
21/// let mut parser = JSONParser::new(input);
22/// ```
23pub struct JSONParser<'a> {
24 pub parser: Parser<'a>,
25}
26
27impl<'a> JSONParser<'a> {
28 /// Create a new JSONParser instance with the given input string.
29 ///
30 /// # Example
31 ///
32 /// ```
33 /// use jsonparser::JSONParser;
34 ///
35 /// let input = r#"
36 /// {
37 /// "name": "John Doe",
38 /// "age": 30
39 /// }
40 /// "#;
41 ///
42 /// let mut parser = JSONParser::new(input);
43 /// ```
44 pub fn new(input: &'a str) -> Self {
45 let lexer = Lexer::new(input);
46 let parser = Parser::new(lexer);
47
48 Self { parser }
49 }
50
51 /// Parse the JSON input to a JSONValue.
52 ///
53 /// # Example
54 ///
55 /// ```
56 /// use jsonparser::JSONParser;
57 ///
58 /// let input = r#"
59 /// {
60 /// "name": "John Doe",
61 /// "age": 30
62 /// }
63 /// "#;
64 ///
65 /// let mut parser = JSONParser::new(input);
66 /// let json = match parser.parse() {
67 /// Ok(value) => value,
68 /// Err(e) => {
69 /// eprintln!("Error: {}", e);
70 /// return;
71 /// }
72 /// };
73 ///
74 /// println!("{:#?}", json["name"].as_str());
75 /// ```
76 pub fn parse(&mut self) -> Result<JSONValue, String> {
77 self.parser.parse()
78 }
79
80 /// Parse the JSON input to a JSONValue.
81 ///
82 /// # Example
83 ///
84 /// ```
85 /// use jsonparser::JSONParser;
86 ///
87 /// let input = r#"
88 /// {
89 /// "name": "John Doe",
90 /// "age": 30
91 /// }
92 /// "#;
93 ///
94 /// let json = match JSONParser::from(input) {
95 /// Ok(value) => value,
96 /// Err(e) => {
97 /// eprintln!("Error: {}", e);
98 /// return;
99 /// }
100 /// };
101 ///
102 /// println!("{:#?}", json["name"].as_str());
103 /// ```
104 pub fn from(input: &'a str) -> Result<JSONValue, String>{
105 let mut parser = JSONParser::new(input);
106
107 parser.parse()
108 }
109}