json_validator/
json_validator.rs

1//! Validator for JSON.  This exists to use with JSON test suites.
2//!
3//! See: https://github.com/nst/JSONTestSuite
4
5use std::env;
6use std::path::PathBuf;
7use trivet::parse_from_path;
8use trivet::parsers::json::JSONParser;
9
10/// Entry point when run from prompt.  This accepts a single argument which must be the
11/// path to a JSON file.  The file is parsed.  If no errors are detected, then a zero is
12/// return (the file is "valid").  Otherwise a one is returned (the file is "invalid").
13pub fn main() {
14    let args: Vec<String> = env::args().collect();
15    if args.len() != 2 {
16        // Missing argument.  Issue a message and stop.
17        println!("Missing filename as only argument.");
18        std::process::exit(0);
19    }
20    let path = PathBuf::from(&args[1]);
21    let mut parser = match parse_from_path(&path) {
22        Ok(parser) => parser,
23        Err(error) => {
24            println!("Error: {}", error);
25            std::process::exit(1)
26        }
27    };
28    match JSONParser::new().parse_value_ws(&mut parser) {
29        Ok(_) => {
30            // If there is any trailing stuff that is not whitespace, then this is not a valid
31            // JSON file.
32            if parser.is_at_eof() {
33                std::process::exit(0)
34            } else {
35                println!("Found unexpected trailing characters after JSON value.");
36                std::process::exit(1);
37            }
38        }
39        Err(error) => {
40            println!("Error: {}", error);
41            std::process::exit(1)
42        }
43    }
44}