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
use regex::Regex;
pub trait JsonPointer {
/// Retourn the json pointer
fn to_json_pointer(&self) -> String;
}
impl JsonPointer for String {
/// Transform a path_field to a json_pointer (json_path).
/// Escape `.` with `\\` if the `.` is not separate two attribute names.
///
/// # Examples
///
/// ```
/// use chewdata::helper::json_pointer::JsonPointer;
///
/// let field_path = "value.sub_value.0.array_value".to_string();
/// let expected_result = "/value/sub_value/0/array_value";
/// assert_eq!(expected_result, field_path.to_json_pointer());
///
/// let field_path = "value.sub_value[0].array_value".to_string();
/// assert_eq!(expected_result, field_path.to_json_pointer());
/// ```
fn to_json_pointer(&self) -> String {
let new_path = format!("/{}", self)
.replace("][", "/")
.replace(']', "")
.replace(['['], "/")
.replace("///", "/")
.replace("//", "/");
let re = Regex::new(r"([^\\])[.]").unwrap();
let new_path = re
.replace_all(new_path.as_str(), "$1/")
.to_string()
.replace("\\.", ".");
new_path
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn to_json_pointer() {
let field_path = "value.sub_value.0.array_value".to_string();
let expected_result = "/value/sub_value/0/array_value";
assert_eq!(expected_result, field_path.to_json_pointer());
let field_path = "value.sub_value[0].array_value".to_string();
assert_eq!(expected_result, field_path.to_json_pointer());
let field_path = "value\\.a.value\\.b".to_string();
let expected_result = "/value.a/value.b";
assert_eq!(expected_result, field_path.to_json_pointer());
}
}