jss_core/into/into_json/
mod.rs1use jsonschema::{Draft, JSONSchema};
2
3use json_value::{to_string_pretty, JsonObject, JsonValue};
4
5use crate::{JssError, JssSchema, JssType, JssValue, Result};
6
7impl JssSchema {
8 pub fn as_json_schema(&self) -> String {
9 to_string_pretty(&JsonValue::from(self))
10 }
11 pub fn as_validator(&self) -> Result<JSONSchema> {
12 let schema = JsonValue::from(self);
13 let compiled = JSONSchema::options().with_draft(Draft::Draft7).compile(&schema)?;
14 return Ok(compiled);
15 }
16 pub fn validate(&self, value: &JsonValue) -> Vec<JssError> {
17 let mut out = vec![];
18 let validator = match self.as_validator() {
19 Ok(o) => o,
20 Err(e) => {
21 out.push(e);
22 return out;
23 }
24 };
25 match validator.validate(value) {
26 Ok(_) => {}
27 Err(e) => {
28 for i in e {
29 out.push(JssError::from(i))
30 }
31 }
32 }
33 return out;
34 }
35 pub fn is_valid(&self, s: &JsonValue) -> bool {
36 self.validate(s).is_empty()
37 }
38}
39
40impl From<&JssSchema> for JsonValue {
41 fn from(jss: &JssSchema) -> Self {
42 if jss.is_anything() {
43 return JsonValue::Bool(true);
44 }
45 if jss.is_noting() {
46 return JsonValue::Bool(false);
47 }
48 let mut object = JsonObject::default();
49 if jss.is_top() {
50 object.insert("title".to_string(), jss.get_name().into());
51 }
52 match jss.is_ref_type() {
53 true => object.insert("$ref".to_string(), jss.get_type().into()),
54 false => object.insert("type".to_string(), jss.get_type().into()),
55 };
56 if jss.has_description() {
57 object.insert("description".to_string(), jss.get_description().into());
58 }
59 for (k, v) in jss.attributes() {
60 object.insert(k.into(), v.clone().into());
61 }
62 if jss.is_top() {
63 let definitions: JsonObject = jss.definitions().map(|(k, v)| (k.clone(), v.into())).collect();
64 object.insert("$defs".to_string(), definitions.into());
65 }
66 let properties: JsonObject = jss.properties().map(|(k, v)| (k.clone(), v.into())).collect();
67 object.insert("properties".to_string(), properties.into());
68
69 JsonValue::Object(object)
70 }
71}
72
73impl From<JssValue> for JsonValue {
74 fn from(jss: JssValue) -> Self {
75 match jss {
76 JssValue::Null => JsonValue::Null,
77 JssValue::Boolean(v) => JsonValue::Bool(v),
78 JssValue::Number(v) => JsonValue::Number(v),
79 JssValue::String(v) => JsonValue::String(v),
80 JssValue::Url(v) => JsonValue::String(v),
81 JssValue::Regex(v) => JsonValue::String(v),
82 JssValue::Array(v) => v.into_iter().map(JsonValue::from).collect(),
83 JssValue::Object(v) => v.into_iter().map(|(k, v)| (k, JsonValue::from(v))).collect(),
84 }
85 }
86}
87
88impl From<JssType> for JsonValue {
89 fn from(jss: JssType) -> Self {
90 JsonValue::String(jss.to_string())
91 }
92}
93
94impl From<&JssType> for JsonValue {
95 fn from(jss: &JssType) -> Self {
96 JsonValue::String(jss.to_string())
97 }
98}