json_dig 0.1.0

a json dig tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
use serde_json::Value;

#[derive(Debug, Clone)]
pub enum PathElement {
    Key(String),
    Index(usize),
    Wildcard, // * 通配符,匹配数组中的所有元素
}

impl From<&str> for PathElement {
    fn from(s: &str) -> Self {
        match s {
            "*" => PathElement::Wildcard,
            _ => PathElement::Key(s.to_string()),
        }
    }
}

impl From<String> for PathElement {
    fn from(s: String) -> Self {
        match s.as_str() {
            "*" => PathElement::Wildcard,
            _ => PathElement::Key(s),
        }
    }
}

impl From<usize> for PathElement {
    fn from(i: usize) -> Self {
        PathElement::Index(i)
    }
}

impl From<i32> for PathElement {
    fn from(i: i32) -> Self {
        PathElement::Index(i as usize)
    }
}

/// 便捷宏:创建路径向量
#[macro_export]
macro_rules! path {
    ($($element:expr),*) => {
        vec![$(PathElement::from($element)),*]
    };
}

/// 主要的提取函数:通过路径提取值(带类型转换和默认值)
pub fn extract<T>(value: &Value, path: &[PathElement], default: T) -> T
where
    T: Clone + for<'de> serde::Deserialize<'de>,
{
    match extract_raw(value, path) {
        Some(v) => serde_json::from_value(v.clone()).unwrap_or(default),
        None => default,
    }
}

/// 提取原始 Value(不做类型转换)
pub fn extract_raw(value: &Value, path: &[PathElement]) -> Option<Value> {
    let mut current = value;
    
    for (i, element) in path.iter().enumerate() {
        match element {
            PathElement::Key(key) => {
                current = current.get(key)?;
            }
            PathElement::Index(index) => {
                current = current.get(*index)?;
            }
            PathElement::Wildcard => {
                // 通配符处理:收集数组中所有元素,并对每个元素应用剩余路径
                let remaining_path = &path[i + 1..];
                return handle_wildcard(current, remaining_path);
            }
        }
    }
    
    Some(current.clone())
}

// 通配符处理函数(支持对象和数组)
fn handle_wildcard(value: &Value, remaining_path: &[PathElement]) -> Option<Value> {
    let mut results = Vec::new();
 
    // 处理数组情况
    if let Some(arr) = value.as_array() {
        for item in arr {
            if let Some(val) = extract_raw(item, remaining_path) {
                match val {
                    Value::Array(a) => results.extend(a),
                    _ => results.push(val),
                }
            }
        }
    }
    // 处理对象情况
    else if let Some(obj) = value.as_object() {
        for (_, val) in obj {
            if let Some(v) = extract_raw(val, remaining_path) {
                match v {
                    Value::Array(a) => results.extend(a),
                    _ => results.push(v),
                }
            }
        }
    }
    
    Some(Value::Array(results))
}


// 为了更方便,也可以为 Value 实现扩展 trait
pub trait JsonExtract {
    fn get<T>(&self, path: &[PathElement], default: T) -> T
    where
        T: Clone + for<'de> serde::Deserialize<'de>;
    fn get_raw(&self, path: &[PathElement]) -> Option<Value>;
}
impl JsonExtract for Value {
    fn get<T>(&self, path: &[PathElement], default: T) -> T
    where
        T: Clone + for<'de> serde::Deserialize<'de>
    {
        extract(self, path, default)
    }
    
    fn get_raw(&self, path: &[PathElement]) -> Option<Value> {
        extract_raw(self, path)
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_basic_paths() {
        let data = json!({
            "data": {
                "items": [
                    {"name": "alice", "age": 20},
                    {"name": "bob", "age": 25}
                ],
                "data.item": "带点号的key",
                "count": 2
            }
        });

        // 字符串路径
        let name: String = extract(&data, &path!["data","items",0,"name"], "unknown".to_string());
        assert_eq!(name, "alice");

        // 混合路径(字符串中包含数字)
        let age: i32 = extract(&data, &path!["data","items",1,"age"], 0);
        assert_eq!(age, 25);

        // 字符串数组路径
        let name2: String = extract(&data, &path!["data", "items", "0", "name"], "unknown".to_string());
        assert_eq!(name2, "unknown");

        // 带点号的 key - 使用字符串数组
        let dot_key: String = extract(&data, &path!["data", "data.item"], "default".to_string());
        assert_eq!(dot_key, "带点号的key");
    }

    #[test]
    fn test_wildcards() {
        let data = json!({
            "users": [
                {"name": "alice", "age": 20},
                {"name": "bob", "age": 25},
                {"name": "charlie", "age": 30}
            ],
            "groups": {
                "admin": {"name": "admin_user", "age": 35},
                "user": {"name": "normal_user", "age": 28}
            }
        });

        // * 通配符 - 提取所有用户年龄
        let ages: Vec<i32> = extract(&data, &path!["users","*","age"], vec![]);
        assert_eq!(ages, vec![20, 25, 30]);

        // * 通配符 - 提取所有组的名字
        let group_names: Vec<String> = extract(&data, &path!["groups","*","name"], vec![]);
        assert!(group_names.contains(&"admin_user".to_string()));
        assert!(group_names.contains(&"normal_user".to_string()));
    }

    // #[test]
    // fn test_recursive_wildcard() {
    //     let data = json!({
    //         "company": {
    //             "departments": [
    //                 {
    //                     "name": "engineering",
    //                     "teams": [
    //                         {"members": [{"age": 25}, {"age": 30}]},
    //                         {"members": [{"age": 28}]}
    //                     ]
    //                 },
    //                 {
    //                     "name": "marketing",
    //                     "teams": [
    //                         {"members": [{"age": 32}, {"age": 27}]}
    //                     ]
    //                 }
    //             ]
    //         }
    //     });

    //     // ** 递归通配符 - 提取所有年龄
    //     let all_ages: Vec<i32> = extract(&data, &path!["**","age"], vec![]);
    //     assert_eq!(all_ages.len(), 5);
    //     assert!(all_ages.contains(&25));
    //     assert!(all_ages.contains(&30));
    //     assert!(all_ages.contains(&28));
    //     assert!(all_ages.contains(&32));
    //     assert!(all_ages.contains(&27));
    // }

    #[test]
    fn test_macro() {
        let data = json!({
            "data": {
                "items": [{"value": 42}]
            }
        });

        let value: i32 = extract(&data, &path!["data", "items", 0, "value"], 0);
        assert_eq!(value, 42);
    }

    #[test]
    fn test_mixed_types() {
        let data = json!({
            "level1": {
                "level2": [
                    {
                        "data.with.dots": "found it"
                    }
                ]
            }
        });

        // 使用字符串数组路径处理带点号的 key
        let result: String = extract(
            &data, 
            &path!["level1", "level2", 0, "data.with.dots"], 
            "not found".to_string()
        );
        assert_eq!(result, "found it");
    }
    
    #[test]
    fn test_extract_string_basic() {
        let json = json!({
            "name": "张三",
            "age": 30,
            "active": true
        });

        assert_eq!(extract(&json, &path!["name"], "".to_string()), "张三");
        assert_eq!(extract(&json, &path!["missing"], "默认值".to_string()), "默认值");
    }

    #[test]
    fn test_extract_string_nested() {
        let json = json!({
            "user": {
                "profile": {
                    "name": "李四",
                    "email": "lisi@example.com"
                }
            }
        });

        assert_eq!(extract(&json, &path!["user","profile","name"], "".to_string()), "李四");
        assert_eq!(extract(&json, &path!["user","profile","email"], "".to_string()), "lisi@example.com");
        assert_eq!(extract(&json, &path!["user","profile","phone"], "".to_string()), "");
    }

    #[test]
    fn test_extract_number_basic() {
        let json = json!({
            "age": 25,
            "score": 95.5,
            "count": 0
        });

        assert_eq!(extract(&json, &path!["age"], 0i32), 25);
        assert_eq!(extract(&json, &path!["score"], 0.0f64), 95.5);
        assert_eq!(extract(&json, &path!["count"], -1i32), 0);
        assert_eq!(extract(&json, &path!["missing"], 100i32), 100);
    }

    #[test]
    fn test_extract_bool_basic() {
        let json = json!({
            "active": true,
            "deleted": false,
            "enabled": null
        });

        assert_eq!(extract(&json, &path!["active"], false), true);
        assert_eq!(extract(&json, &path!["deleted"], true), false);
        assert_eq!(extract(&json, &path!["missing"], true), true);
        // null 值应该返回默认值
        assert_eq!(extract(&json, &path!["enabled"], false), false);
    }

    #[test]
    fn test_array_access() {
        let json = json!({
            "users": [
                {"name": "用户1", "age": 20},
                {"name": "用户2", "age": 25},
                {"name": "用户3", "age": 30}
            ],
            "tags": ["rust", "json", "serde"]
        });

        assert_eq!(extract(&json, &path!["users",0,"name"], "".to_string()), "用户1");
        assert_eq!(extract(&json, &path!["users",1,"age"], 0i32), 25);
        assert_eq!(extract(&json, &path!["users",2,"name"], "".to_string()), "用户3");
        assert_eq!(extract(&json, &path!["tags",0], "".to_string()), "rust");
        assert_eq!(extract(&json, &path!["tags",2], "".to_string()), "serde");
    }

    #[test]
    fn test_array_out_of_bounds() {
        let json = json!({
            "items": ["a", "b", "c"]
        });

        assert_eq!(extract(&json, &path!["items",5], "默认".to_string()), "默认");
        assert_eq!(extract(&json, &path!["items",10], 999i32), 999);
    }

    #[test]
    fn test_complex_nested_structure() {
        let json = json!({
            "company": {
                "name": "科技公司",
                "departments": [
                    {
                        "name": "研发部",
                        "employees": [
                            {
                                "name": "王五",
                                "position": "工程师",
                                "skills": ["Rust", "Python", "JavaScript"]
                            },
                            {
                                "name": "赵六",
                                "position": "架构师",
                                "skills": ["Go", "Docker", "Kubernetes"]
                            }
                        ]
                    }
                ]
            }
        });

        assert_eq!(
            extract(&json, &path!["company","name"], "".to_string()),
            "科技公司"
        );
        assert_eq!(
            extract(&json, &path!["company","departments",0,"name"], "".to_string()),
            "研发部"
        );
        assert_eq!(
            extract(&json, &path!["company","departments",0,"employees",0,"name"], "".to_string()),
            "王五"
        );
        assert_eq!(
            extract(&json, &path!["company","departments",0,"employees",1,"position"], "".to_string()),
            "架构师"
        );
        assert_eq!(
            extract(&json, &path!["company","departments",0,"employees",0,"skills",0], "".to_string()),
            "Rust"
        );
    }

    
 

    #[test]
    fn test_type_conversion_failures() {
        let json = json!({
            "string_value": "不是数字",
            "number_value": 42,
            "bool_string": "true",
            "null_value": null
        });

        // 尝试将字符串解析为数字,应该返回默认值
        assert_eq!(extract(&json, &path!["string_value"], 999i32), 999);
        
        // 尝试将数字解析为字符串,应该成功
        assert_eq!(extract(&json, &path!["number_value"], "default".to_string()), "default");
        
        // 尝试将字符串解析为布尔值,应该返回默认值
        assert_eq!(extract(&json, &path!["bool_string"], false), false);
        
        // null 值应该返回默认值
        assert_eq!(extract(&json, &path!["null_value"], "默认".to_string()), "默认");
    }

    #[test]
    fn test_extract_raw_value() {
        let json = json!({
            "object": {
                "nested": "value"
            },
            "array": [1, 2, 3],
            "string": "text",
            "number": 42,
            "boolean": true,
            "null": null
        });

        // 测试提取不同类型的原始值
        let obj = extract(&json, &path!["object"], json!({}));
        assert_eq!(obj, json!({ "nested": "value" }));

        let arr = extract(&json, &path!["array"], json!([]));
        assert_eq!(arr, json!([1, 2, 3]));

        let str_val = extract(&json, &path!["string"], "".to_string());
        assert_eq!(str_val, "text");

        let num_val = extract(&json, &path!["number"], 0i32);
        assert_eq!(num_val, 42);

        let null_type: Vec<Value> = extract(&json, &path!["null"], vec![]);
        // assert_eq!(null_type, json!(null));
        println!("null_type:{:?}", null_type);


      
    }

    #[test]
    fn test_xx_deep() {
        let json = json!(
            {
                "people": {
                    "group1": {
                        "member1": {
                           
                            "age": {"30":30}
                       
                        },
                        "member2": {
                            
                            "age": ["25"]
                           
                        }
                    },
                    "group2": {
                        "member3": {
                            "age": [40,4000]
                        },
                        "member4": {
                           
                            "age": "STRING35"
                            
                        },
                        "member5": {
                            
                            "age": null
                           
                        },
                        "member6": {
                            
                            "age": false
                           
                        }
                    }
                } 
            }
        );
        let age: Vec<Value> = extract(&json, &path!["*","*","*","age"], vec![]);
        println!("age:{:?}", age);
        
       
    }

}