Function validate_json

Source
pub fn validate_json(json: &str) -> Result<(), ConfigExprError>
Expand description

便利方法:验证JSON规则是否合法

Examples found in repository?
examples/basic_usage.rs (line 44)
4fn main() -> Result<(), Box<dyn std::error::Error>> {
5    // 示例1: 基本用法 - 直接从JSON字符串评估
6    println!("=== 示例1: 基本用法 ===");
7
8    let json_rules = r#"
9    {
10        "rules": [
11            {
12                "if": {
13                    "and": [
14                        { "field": "platform", "op": "contains", "value": "RTD" },
15                        { "field": "region", "op": "equals", "value": "CN" }
16                    ]
17                },
18                "then": "chip_rtd_cn"
19            },
20            {
21                "if": {
22                    "or": [
23                        { "field": "platform", "op": "equals", "value": "MT9950" },
24                        { "field": "platform", "op": "equals", "value": "MT9638" }
25                    ]
26                },
27                "then": "chip_mt"
28            },
29            {
30                "if": {
31                    "field": "platform",
32                    "op": "prefix",
33                    "value": "Hi"
34                },
35                "then": "chip_hi"
36            }
37        ],
38        "fallback": "default_chip"
39    }
40    "#;
41
42    // 验证规则是否合法
43    println!("验证规则...");
44    validate_json(json_rules)?;
45    println!("✓ 规则验证通过");
46
47    // 测试不同的参数组合
48    let test_cases = vec![
49        (
50            vec![("platform", "RTD-2000"), ("region", "CN")],
51            "应该匹配 chip_rtd_cn",
52        ),
53        (vec![("platform", "MT9950")], "应该匹配 chip_mt"),
54        (vec![("platform", "Hi3516")], "应该匹配 chip_hi"),
55        (vec![("platform", "Unknown")], "应该使用 fallback"),
56    ];
57
58    for (params_vec, description) in test_cases {
59        let mut params = HashMap::new();
60        for (key, value) in params_vec {
61            params.insert(key.to_string(), value.to_string());
62        }
63
64        let result = evaluate_json(json_rules, &params)?;
65        println!("测试: {} -> {:?}", description, result);
66    }
67
68    // 示例2: JSON对象结果
69    println!("\n=== 示例2: JSON对象结果 ===");
70
71    let json_with_object = r#"
72    {
73        "rules": [
74            {
75                "if": {
76                    "field": "platform",
77                    "op": "equals",
78                    "value": "RTD"
79                },
80                "then": {
81                    "chip": "rtd",
82                    "config": {
83                        "memory": "2GB",
84                        "cpu": "ARM",
85                        "features": ["wifi", "bluetooth"]
86                    }
87                }
88            }
89        ]
90    }
91    "#;
92
93    let mut params = HashMap::new();
94    params.insert("platform".to_string(), "RTD".to_string());
95
96    let result = evaluate_json(json_with_object, &params)?;
97    if let Some(RuleResult::Object(obj)) = result {
98        println!("匹配到JSON对象结果:");
99        println!("  chip: {}", obj["chip"]);
100        println!("  memory: {}", obj["config"]["memory"]);
101        println!("  cpu: {}", obj["config"]["cpu"]);
102        println!("  features: {:?}", obj["config"]["features"]);
103    }
104
105    // 示例3: 使用ConfigEvaluator结构体
106    println!("\n=== 示例3: 使用ConfigEvaluator ===");
107
108    let evaluator = ConfigEvaluator::from_json(json_rules)?;
109
110    let mut params = HashMap::new();
111    params.insert("platform".to_string(), "Hi3516DV300".to_string());
112
113    let result = evaluator.evaluate(&params);
114    println!("Hi3516DV300 -> {:?}", result);
115
116    // 示例4: 正则表达式匹配
117    println!("\n=== 示例4: 正则表达式匹配 ===");
118
119    let regex_rules = r#"
120    {
121        "rules": [
122            {
123                "if": {
124                    "field": "version",
125                    "op": "regex",
126                    "value": "^v\\d+\\.\\d+\\.\\d+$"
127                },
128                "then": "valid_version"
129            }
130        ],
131        "fallback": "invalid_version"
132    }
133    "#;
134
135    let test_versions = vec!["v1.2.3", "v10.0.1", "1.2.3", "v1.2"];
136
137    for version in test_versions {
138        let mut params = HashMap::new();
139        params.insert("version".to_string(), version.to_string());
140
141        let result = evaluate_json(regex_rules, &params)?;
142        println!("版本 {} -> {:?}", version, result);
143    }
144
145    // 示例5: 复杂嵌套条件
146    println!("\n=== 示例5: 复杂嵌套条件 ===");
147
148    let complex_rules = r#"
149    {
150        "rules": [
151            {
152                "if": {
153                    "and": [
154                        {
155                            "or": [
156                                { "field": "platform", "op": "prefix", "value": "Hi" },
157                                { "field": "platform", "op": "prefix", "value": "MT" }
158                            ]
159                        },
160                        { "field": "region", "op": "equals", "value": "CN" },
161                        { "field": "env", "op": "contains", "value": "prod" }
162                    ]
163                },
164                "then": {
165                    "chip_type": "cn_production",
166                    "optimization": "high"
167                }
168            }
169        ]
170    }
171    "#;
172
173    let mut params = HashMap::new();
174    params.insert("platform".to_string(), "Hi3516".to_string());
175    params.insert("region".to_string(), "CN".to_string());
176    params.insert("env".to_string(), "production".to_string());
177
178    let result = evaluate_json(complex_rules, &params)?;
179    println!("复杂条件匹配结果: {:?}", result);
180
181    // 示例6: 数值比较操作符
182    println!("\n=== 示例6: 数值比较操作符 ===");
183
184    let numeric_rules = r#"
185    {
186        "rules": [
187            {
188                "if": {
189                    "field": "score",
190                    "op": "ge",
191                    "value": "90"
192                },
193                "then": "excellent"
194            },
195            {
196                "if": {
197                    "field": "score",
198                    "op": "ge",
199                    "value": "80"
200                },
201                "then": "good"
202            },
203            {
204                "if": {
205                    "field": "score",
206                    "op": "ge",
207                    "value": "60"
208                },
209                "then": "pass"
210            }
211        ],
212        "fallback": "fail"
213    }
214    "#;
215
216    let test_scores = vec!["95", "85", "75", "50", "not_a_number"];
217
218    for score in test_scores {
219        let mut params = HashMap::new();
220        params.insert("score".to_string(), score.to_string());
221
222        let result = evaluate_json(numeric_rules, &params)?;
223        println!("分数 {} -> {:?}", score, result);
224    }
225
226    // 示例7: 混合条件(字符串和数值)
227    println!("\n=== 示例7: 混合条件 ===");
228
229    let mixed_rules = r#"
230    {
231        "rules": [
232            {
233                "if": {
234                    "and": [
235                        { "field": "category", "op": "equals", "value": "premium" },
236                        { "field": "price", "op": "gt", "value": "100.0" },
237                        { "field": "rating", "op": "ge", "value": "4.5" }
238                    ]
239                },
240                "then": {
241                    "tier": "premium",
242                    "discount": 0.1,
243                    "features": ["priority_support", "advanced_analytics"]
244                }
245            },
246            {
247                "if": {
248                    "and": [
249                        { "field": "category", "op": "equals", "value": "standard" },
250                        { "field": "price", "op": "le", "value": "50.0" }
251                    ]
252                },
253                "then": {
254                    "tier": "standard",
255                    "discount": 0.05
256                }
257            }
258        ]
259    }
260    "#;
261
262    let mut params = HashMap::new();
263    params.insert("category".to_string(), "premium".to_string());
264    params.insert("price".to_string(), "150.99".to_string());
265    params.insert("rating".to_string(), "4.8".to_string());
266
267    let result = evaluate_json(mixed_rules, &params)?;
268    println!("混合条件匹配结果: {:?}", result);
269
270    Ok(())
271}