Repository navigation
Expand file tree
/
Copy pathjson_utils.rs
More file actions
657 lines (571 loc) · 18.8 KB
/
Copy pathjson_utils.rs
File metadata and controls
657 lines (571 loc) · 18.8 KB
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! JSON utilities.
//!
//! Provides utilities for working with JSON including
//! path-based access, transformation, and validation.
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::error::{CortexError, Result};
/// JSON path for navigating JSON structures.
#[derive(Debug, Clone)]
pub struct JsonPath {
segments: Vec<PathSegment>,
}
impl JsonPath {
/// Parse a path string.
pub fn parse(path: &str) -> Result<Self> {
let mut segments = Vec::new();
if path.is_empty() || path == "$" {
return Ok(Self { segments });
}
let path = path.strip_prefix("$.").unwrap_or(path);
for part in path.split('.') {
if part.is_empty() {
continue;
}
// Check for array index
if part.contains('[') && part.ends_with(']') {
let bracket_pos = part.find('[').unwrap();
let key = &part[..bracket_pos];
let index_str = &part[bracket_pos + 1..part.len() - 1];
if !key.is_empty() {
segments.push(PathSegment::Key(key.to_string()));
}
let index: usize = index_str.parse().map_err(|_| {
CortexError::InvalidInput(format!("Invalid array index: {index_str}"))
})?;
segments.push(PathSegment::Index(index));
} else {
segments.push(PathSegment::Key(part.to_string()));
}
}
Ok(Self { segments })
}
/// Get value at path.
pub fn get<'a>(&self, value: &'a Value) -> Option<&'a Value> {
let mut current = value;
for segment in &self.segments {
match segment {
PathSegment::Key(key) => {
current = current.get(key)?;
}
PathSegment::Index(idx) => {
current = current.get(idx)?;
}
}
}
Some(current)
}
/// Get mutable value at path.
pub fn get_mut<'a>(&self, value: &'a mut Value) -> Option<&'a mut Value> {
let mut current = value;
for segment in &self.segments {
match segment {
PathSegment::Key(key) => {
current = current.get_mut(key)?;
}
PathSegment::Index(idx) => {
current = current.get_mut(idx)?;
}
}
}
Some(current)
}
/// Set value at path.
pub fn set(&self, root: &mut Value, new_value: Value) -> Result<()> {
if self.segments.is_empty() {
*root = new_value;
return Ok(());
}
let parent_path = Self {
segments: self.segments[..self.segments.len() - 1].to_vec(),
};
let parent = parent_path
.get_mut(root)
.ok_or_else(|| CortexError::NotFound("Parent path not found".to_string()))?;
match &self.segments[self.segments.len() - 1] {
PathSegment::Key(key) => {
if let Some(obj) = parent.as_object_mut() {
obj.insert(key.clone(), new_value);
} else {
return Err(CortexError::InvalidInput(
"Parent is not an object".to_string(),
));
}
}
PathSegment::Index(idx) => {
if let Some(arr) = parent.as_array_mut() {
if *idx < arr.len() {
arr[*idx] = new_value;
} else {
return Err(CortexError::InvalidInput("Index out of bounds".to_string()));
}
} else {
return Err(CortexError::InvalidInput(
"Parent is not an array".to_string(),
));
}
}
}
Ok(())
}
/// Delete value at path.
pub fn delete(&self, root: &mut Value) -> Result<Option<Value>> {
if self.segments.is_empty() {
return Err(CortexError::InvalidInput("Cannot delete root".to_string()));
}
let parent_path = Self {
segments: self.segments[..self.segments.len() - 1].to_vec(),
};
let parent = parent_path
.get_mut(root)
.ok_or_else(|| CortexError::NotFound("Parent path not found".to_string()))?;
match &self.segments[self.segments.len() - 1] {
PathSegment::Key(key) => {
if let Some(obj) = parent.as_object_mut() {
Ok(obj.remove(key))
} else {
Err(CortexError::InvalidInput(
"Parent is not an object".to_string(),
))
}
}
PathSegment::Index(idx) => {
if let Some(arr) = parent.as_array_mut() {
if *idx < arr.len() {
Ok(Some(arr.remove(*idx)))
} else {
Err(CortexError::InvalidInput("Index out of bounds".to_string()))
}
} else {
Err(CortexError::InvalidInput(
"Parent is not an array".to_string(),
))
}
}
}
}
/// Check if path exists.
pub fn exists(&self, value: &Value) -> bool {
self.get(value).is_some()
}
/// Convert to string.
pub fn to_string(&self) -> String {
let mut parts = vec!["$".to_string()];
for segment in &self.segments {
match segment {
PathSegment::Key(key) => parts.push(key.clone()),
PathSegment::Index(idx) => parts.push(format!("[{idx}]")),
}
}
parts.join(".")
}
}
/// Path segment.
#[derive(Debug, Clone)]
enum PathSegment {
Key(String),
Index(usize),
}
/// JSON merge.
pub fn merge(base: &mut Value, other: &Value) {
match (base, other) {
(Value::Object(base_obj), Value::Object(other_obj)) => {
for (key, value) in other_obj {
if let Some(base_value) = base_obj.get_mut(key) {
merge(base_value, value);
} else {
base_obj.insert(key.clone(), value.clone());
}
}
}
(base, other) => {
*base = other.clone();
}
}
}
/// JSON diff.
pub fn diff(old: &Value, new: &Value) -> Vec<JsonDiff> {
let mut diffs = Vec::new();
diff_recursive(old, new, String::new(), &mut diffs);
diffs
}
fn diff_recursive(old: &Value, new: &Value, path: String, diffs: &mut Vec<JsonDiff>) {
if old == new {
return;
}
match (old, new) {
(Value::Object(old_obj), Value::Object(new_obj)) => {
// Check for removed keys
for key in old_obj.keys() {
if !new_obj.contains_key(key) {
let key_path = if path.is_empty() {
key.clone()
} else {
format!("{path}.{key}")
};
diffs.push(JsonDiff::Removed {
path: key_path,
value: old_obj.get(key).unwrap().clone(),
});
}
}
// Check for added and changed keys
for (key, new_value) in new_obj {
let key_path = if path.is_empty() {
key.clone()
} else {
format!("{path}.{key}")
};
if let Some(old_value) = old_obj.get(key) {
diff_recursive(old_value, new_value, key_path, diffs);
} else {
diffs.push(JsonDiff::Added {
path: key_path,
value: new_value.clone(),
});
}
}
}
(Value::Array(old_arr), Value::Array(new_arr)) => {
let max_len = old_arr.len().max(new_arr.len());
for i in 0..max_len {
let idx_path = if path.is_empty() {
format!("[{i}]")
} else {
format!("{path}[{i}]")
};
match (old_arr.get(i), new_arr.get(i)) {
(Some(old_val), Some(new_val)) => {
diff_recursive(old_val, new_val, idx_path, diffs);
}
(Some(old_val), None) => {
diffs.push(JsonDiff::Removed {
path: idx_path,
value: old_val.clone(),
});
}
(None, Some(new_val)) => {
diffs.push(JsonDiff::Added {
path: idx_path,
value: new_val.clone(),
});
}
(None, None) => {}
}
}
}
_ => {
diffs.push(JsonDiff::Changed {
path,
old_value: old.clone(),
new_value: new.clone(),
});
}
}
}
/// JSON diff entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum JsonDiff {
/// Value was added.
Added { path: String, value: Value },
/// Value was removed.
Removed { path: String, value: Value },
/// Value was changed.
Changed {
path: String,
old_value: Value,
new_value: Value,
},
}
impl JsonDiff {
/// Get path.
pub fn path(&self) -> &str {
match self {
Self::Added { path, .. } => path,
Self::Removed { path, .. } => path,
Self::Changed { path, .. } => path,
}
}
}
/// JSON flattener.
pub fn flatten(value: &Value) -> HashMap<String, Value> {
let mut result = HashMap::new();
flatten_recursive(value, String::new(), &mut result);
result
}
fn flatten_recursive(value: &Value, prefix: String, result: &mut HashMap<String, Value>) {
match value {
Value::Object(obj) => {
for (key, val) in obj {
let new_prefix = if prefix.is_empty() {
key.clone()
} else {
format!("{prefix}.{key}")
};
flatten_recursive(val, new_prefix, result);
}
}
Value::Array(arr) => {
for (idx, val) in arr.iter().enumerate() {
let new_prefix = format!("{prefix}[{idx}]");
flatten_recursive(val, new_prefix, result);
}
}
_ => {
result.insert(prefix, value.clone());
}
}
}
/// JSON unflatten.
pub fn unflatten(flat: &HashMap<String, Value>) -> Value {
let mut result = Value::Object(Map::new());
for (path, value) in flat {
let json_path = JsonPath::parse(path).unwrap_or(JsonPath { segments: vec![] });
// Create path
let _ = ensure_path(&mut result, &json_path);
let _ = json_path.set(&mut result, value.clone());
}
result
}
/// Ensure path exists in value.
fn ensure_path(root: &mut Value, path: &JsonPath) -> Result<()> {
let mut current = root;
for (i, segment) in path.segments.iter().enumerate() {
match segment {
PathSegment::Key(key) => {
if !current.is_object() {
*current = Value::Object(Map::new());
}
let obj = current.as_object_mut().unwrap();
if !obj.contains_key(key) {
// Look ahead to determine type
let next_is_index = path
.segments
.get(i + 1)
.map(|s| matches!(s, PathSegment::Index(_)))
.unwrap_or(false);
if next_is_index {
obj.insert(key.clone(), Value::Array(vec![]));
} else {
obj.insert(key.clone(), Value::Object(Map::new()));
}
}
current = obj.get_mut(key).unwrap();
}
PathSegment::Index(idx) => {
if !current.is_array() {
*current = Value::Array(vec![]);
}
let arr = current.as_array_mut().unwrap();
while arr.len() <= *idx {
arr.push(Value::Null);
}
current = &mut arr[*idx];
}
}
}
Ok(())
}
/// JSON query builder.
pub struct JsonQuery {
filters: Vec<Box<dyn Fn(&Value) -> bool + Send + Sync>>,
}
impl JsonQuery {
/// Create a new query.
pub fn new() -> Self {
Self {
filters: Vec::new(),
}
}
/// Add equals filter.
pub fn equals(mut self, path: &str, expected: Value) -> Self {
let path = JsonPath::parse(path).unwrap_or(JsonPath { segments: vec![] });
self.filters.push(Box::new(move |v| {
path.get(v).map(|v| v == &expected).unwrap_or(false)
}));
self
}
/// Add contains filter (for strings/arrays).
pub fn contains(mut self, path: &str, needle: &str) -> Self {
let path = JsonPath::parse(path).unwrap_or(JsonPath { segments: vec![] });
let needle = needle.to_string();
self.filters.push(Box::new(move |v| {
if let Some(val) = path.get(v)
&& let Some(s) = val.as_str()
{
return s.contains(&needle);
}
false
}));
self
}
/// Add exists filter.
pub fn exists(mut self, path: &str) -> Self {
let path = JsonPath::parse(path).unwrap_or(JsonPath { segments: vec![] });
self.filters.push(Box::new(move |v| path.exists(v)));
self
}
/// Add greater than filter.
pub fn gt(mut self, path: &str, threshold: f64) -> Self {
let path = JsonPath::parse(path).unwrap_or(JsonPath { segments: vec![] });
self.filters.push(Box::new(move |v| {
path.get(v)
.and_then(serde_json::Value::as_f64)
.map(|n| n > threshold)
.unwrap_or(false)
}));
self
}
/// Add less than filter.
pub fn lt(mut self, path: &str, threshold: f64) -> Self {
let path = JsonPath::parse(path).unwrap_or(JsonPath { segments: vec![] });
self.filters.push(Box::new(move |v| {
path.get(v)
.and_then(serde_json::Value::as_f64)
.map(|n| n < threshold)
.unwrap_or(false)
}));
self
}
/// Check if value matches query.
pub fn matches(&self, value: &Value) -> bool {
self.filters.iter().all(|f| f(value))
}
/// Filter array of values.
pub fn filter<'a>(&self, values: &'a [Value]) -> Vec<&'a Value> {
values.iter().filter(|v| self.matches(v)).collect()
}
}
impl Default for JsonQuery {
fn default() -> Self {
Self::new()
}
}
/// Pretty print JSON.
pub fn pretty_print(value: &Value) -> String {
serde_json::to_string_pretty(value).unwrap_or_else(|_| value.to_string())
}
/// Compact JSON.
pub fn compact(value: &Value) -> String {
value.to_string()
}
/// Validate JSON against schema (simplified).
pub fn validate_type(value: &Value, expected_type: JsonType) -> bool {
match expected_type {
JsonType::Null => value.is_null(),
JsonType::Bool => value.is_boolean(),
JsonType::Number => value.is_number(),
JsonType::String => value.is_string(),
JsonType::Array => value.is_array(),
JsonType::Object => value.is_object(),
}
}
/// JSON type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JsonType {
Null,
Bool,
Number,
String,
Array,
Object,
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_json_path_parse() {
let path = JsonPath::parse("user.name").unwrap();
assert_eq!(path.segments.len(), 2);
let path = JsonPath::parse("items[0].value").unwrap();
assert_eq!(path.segments.len(), 3);
}
#[test]
fn test_json_path_get() {
let data = json!({
"user": {
"name": "Alice",
"age": 30
},
"items": [1, 2, 3]
});
let path = JsonPath::parse("user.name").unwrap();
assert_eq!(path.get(&data), Some(&json!("Alice")));
let path = JsonPath::parse("items[1]").unwrap();
assert_eq!(path.get(&data), Some(&json!(2)));
}
#[test]
fn test_json_path_set() {
let mut data = json!({
"user": { "name": "Alice" }
});
let path = JsonPath::parse("user.name").unwrap();
path.set(&mut data, json!("Bob")).unwrap();
assert_eq!(data["user"]["name"], json!("Bob"));
}
#[test]
fn test_json_merge() {
let mut base = json!({
"a": 1,
"b": { "c": 2 }
});
let other = json!({
"b": { "d": 3 },
"e": 4
});
merge(&mut base, &other);
assert_eq!(base["a"], json!(1));
assert_eq!(base["b"]["c"], json!(2));
assert_eq!(base["b"]["d"], json!(3));
assert_eq!(base["e"], json!(4));
}
#[test]
fn test_json_diff() {
let old = json!({ "a": 1, "b": 2 });
let new = json!({ "a": 1, "c": 3 });
let diffs = diff(&old, &new);
assert!(
diffs
.iter()
.any(|d| matches!(d, JsonDiff::Removed { path, .. } if path == "b"))
);
assert!(
diffs
.iter()
.any(|d| matches!(d, JsonDiff::Added { path, .. } if path == "c"))
);
}
#[test]
fn test_json_flatten() {
let data = json!({
"user": {
"name": "Alice"
},
"items": [1, 2]
});
let flat = flatten(&data);
assert_eq!(flat.get("user.name"), Some(&json!("Alice")));
assert_eq!(flat.get("items[0]"), Some(&json!(1)));
}
#[test]
fn test_json_query() {
let data = vec![
json!({ "name": "Alice", "age": 30 }),
json!({ "name": "Bob", "age": 25 }),
json!({ "name": "Charlie", "age": 35 }),
];
let query = JsonQuery::new().gt("age", 28.0);
let results = query.filter(&data);
assert_eq!(results.len(), 2);
}
#[test]
fn test_validate_type() {
assert!(validate_type(&json!("test"), JsonType::String));
assert!(validate_type(&json!(42), JsonType::Number));
assert!(validate_type(&json!([1, 2]), JsonType::Array));
assert!(!validate_type(&json!("test"), JsonType::Number));
}
}