8次发布
0.3.3 | 2020年1月20日 |
---|---|
0.3.2 | 2019年11月11日 |
0.3.0 | 2019年9月7日 |
0.2.0 | 2019年9月7日 |
0.1.1 | 2019年8月18日 |
#1079 in 编码
35 每月下载量
用于 4 crates
63KB
1.5K SLoC
jddf-rust
在docs.rs上的文档: https://docs.rs/jddf
此crate是JSON数据定义格式的Rust实现。您可以使用它来
- 验证输入数据是否符合模式,
- 获取与该输入数据相关的验证错误列表,或者
- 在JSON数据定义格式之上构建自己的自定义工具。
安装
要将 jddf
作为依赖项添加到您的库中,请在您的 Cargo.toml
中添加以下内容
[dependencies]
jddf = "0.3"
用法
docs.rs上的详细文档进行了更详细的说明,但在这里简要说明如何使用此crate来验证输入数据
use serde_json::json;
use jddf::{Schema, SerdeSchema, Validator, ValidationError};
use failure::Error;
use std::collections::HashSet;
fn main() -> Result<(), Error> {
let demo_schema_data = r#"
{
"properties": {
"name": { "type": "string" },
"age": { "type": "float64" },
"phones": {
"elements": { "type": "string" }
}
}
}
"#;
// The SerdeSchema type is a serde-friendly format for representing
// schemas.
let demo_schema: SerdeSchema = serde_json::from_str(demo_schema_data)?;
// The Schema type is a higher-level format that does more validity
// checks.
let demo_schema = Schema::from_serde(demo_schema).unwrap();
// Validator can quickly check if an instance satisfies some schema.
// With the new_with_config constructor, you can configure how many
// errors to return, and how to handle the possibility of a
// circularly-defined schema.
let validator = Validator::new();
let input_ok = json!({
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
});
let validation_errors_ok = validator.validate(&demo_schema, &input_ok)?;
assert!(validation_errors_ok.is_empty());
let input_bad = json!({
"age": "43",
"phones": [
"+44 1234567",
442345678
]
});
// Each ValidationError holds paths to the bad part of the input, as
// well as the part of the schema which rejected it.
//
// For testing purposes, we'll sort the errors so that their order is
// predictable.
let mut validation_errors_bad = validator.validate(&demo_schema, &input_bad)?;
validation_errors_bad.sort_by_key(|err| err.instance_path().to_string());
assert_eq!(validation_errors_bad.len(), 3);
// "name" is required
assert_eq!(validation_errors_bad[0].instance_path().to_string(), "");
assert_eq!(validation_errors_bad[0].schema_path().to_string(), "/properties/name");
// "age" has the wrong type
assert_eq!(validation_errors_bad[1].instance_path().to_string(), "/age");
assert_eq!(validation_errors_bad[1].schema_path().to_string(), "/properties/age/type");
// "phones[1]" has the wrong type
assert_eq!(validation_errors_bad[2].instance_path().to_string(), "/phones/1");
assert_eq!(validation_errors_bad[2].schema_path().to_string(), "/properties/phones/elements/type");
Ok(())
}
依赖项
~1.7–2.7MB
~53K SLoC