Crates.io | jsonparser |
lib.rs | jsonparser |
version | 0.2.1 |
source | src |
created_at | 2024-02-12 21:42:17.830395 |
updated_at | 2024-02-17 21:00:06.901277 |
description | A Rust crate for efficient parsing and validation of JSON data into strongly typed Rust data structures, enabling data integrity checks. |
homepage | |
repository | https://github.com/nethriis/json-parser |
max_upload_size | |
id | 1137331 |
size | 60,207 |
This Rust crate provides a robust and efficient solution for parsing JSON data into Rust's strongly-typed data structures. It's designed to simplify the process of converting JSON text into Rust types and allows you to validate your JSON data with schema-based validation, making it easier to work with JSON data in Rust applications.
To use this crate in your project, add it to your Cargo.toml
:
[dependencies]
jsonparser = "0.2.1"
Then, import it in your Rust file:
use jsonparser::*;
To parse a JSON string into a Rust JSONValue
, use the from
function provided by the crate:
use jsonparser::JSONParser;
let input = r#"
{
"name": "John Doe",
"age": 30,
"is_student": false
}
"#;
match JSONParser::from(input) {
Ok(json) => println!("{:#?}", json),
Err(e) => eprintln!("Failed to parse JSON: {}", e),
}
Once parsed, access the data using the .get()
method or the indexing syntax for both objects and arrays:
// Using `.get()` method
if let Some(name) = json.get("name").and_then(|v| v.as_str()) {
println!("Name: {}", name);
}
// Using indexing syntax
let age = &json["age"];
if let Some(age) = age.as_f64() {
println!("Age: {}", age);
}
To serialize a Rust data structure into a JSON string, use the serialize
method:
use jsonparser::{JSONParser, JSONValue};
let json: JSONValue = JSONParser::from(r#"{ "name": "John Doe", "age": 30, "is_student": false }"#).unwrap();
let serialized = json.serialize();
assert_eq!(serialized, r#"{"name":"John Doe","age":30,"is_student":false}"#);
To validate a JSONValue, use the validate
method:
use jsonparser::{JSONParser, JSONValue, JSONSchema, StringType, NumberType, BooleanType};
let json: JSONValue = JSONParser::from(r#"{ "name": "John Doe", "age": 30, "is_student": false }"#).unwrap();
let schema = JSONSchema::new([
("name", StringType::new().min_length(3).trim().boxed()),
("age", NumberType::new().gt(18).lt(100).boxed()),
("is_student", BooleanType::new().falsy().boxed()),
]);
assert!(schema.validate(&json).is_ok());
Contributions are welcome! If you have suggestions for improvements or find any issues, please open an issue or submit a pull request on GitHub.
This project is licensed under the Apache-2.0 license.