Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for type in json schema to be a list #138

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions src/json_schema/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
mod parsing;
mod types;

pub use types::*;

use serde_json::Value;
pub use types::*;

use crate::JsonSchemaParserError;

Expand All @@ -24,9 +23,10 @@ pub fn to_regex(json: &Value, whitespace_pattern: Option<&str>) -> Result<String

#[cfg(test)]
mod tests {
use super::*;
use regex::Regex;

use super::*;

fn should_match(re: &Regex, value: &str) {
// Asserts that value is fully matched.
match re.find(value) {
Expand Down Expand Up @@ -918,8 +918,26 @@ mod tests {
"username@example..com", // double dot in domain name
"username@.example..com", // multiple errors in domain
]
)
),

// ==========================================================
// Multiple types
// ==========================================================
(
r#"{
"title": "Foo",
"type": ["string", "number", "boolean"]
}"#,
format!(r#"((?:"{STRING_INNER}*")|(?:{NUMBER})|(?:{BOOLEAN}))"#).as_str(),
vec!["12.3", "true", r#""a""#],
vec![
"null",
"",
"12true",
r#"1.3"a""#,
r#"12.3true"a""#,
],
)
] {
let json: Value = serde_json::from_str(schema).expect("Can't parse json");
let result = to_regex(&json, None).expect("To regex failed");
Expand Down
34 changes: 30 additions & 4 deletions src/json_schema/parsing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,10 +315,21 @@ impl<'a> Parser<'a> {
}

fn parse_type(&mut self, obj: &serde_json::Map<String, Value>) -> Result<String> {
let instance_type = obj["type"]
.as_str()
.ok_or_else(|| JsonSchemaParserError::TypeMustBeAString)?;
match instance_type {
let instance_types = if let Some(instance_type) = obj["type"].as_str() {
vec![instance_type]
} else if let Some(instance_types) = obj["type"].as_array() {
instance_types
.iter()
.map(|instance_type| match instance_type.as_str() {
Some(instance_type) => Ok(instance_type),
None => Err(JsonSchemaParserError::TypeMustBeAString),
})
.collect::<Result<Vec<&str>>>()?
} else {
return Err(JsonSchemaParserError::TypeMustBeAString);
};

let mut parse_instance_type = |instance_type: &str| match instance_type {
"string" => self.parse_string_type(obj),
"number" => self.parse_number_type(obj),
"integer" => self.parse_integer_type(obj),
Expand All @@ -329,6 +340,21 @@ impl<'a> Parser<'a> {
_ => Err(JsonSchemaParserError::UnsupportedType(Box::from(
instance_type,
))),
};

if instance_types.len() == 1 {
parse_instance_type(instance_types[0])
} else {
let xor_patterns = instance_types
.into_iter()
.map(|instance_type| {
let sub_regex = parse_instance_type(instance_type)?;

Ok(format!(r"(?:{})", sub_regex))
})
.collect::<Result<Vec<String>>>()?;

Ok(format!(r"({})", xor_patterns.join("|")))
}
}

Expand Down
Loading