Skip to main content

json_patch_ext/
lib.rs

1//! This module provides some unofficial "extensions" to the [jsonpatch](https://jsonpatch.com)
2//! format for describing changes to a JSON document.  In particular, it adds the `*` operator as a
3//! valid token for arrays in a JSON document.  It means: apply this change to all elements of this
4//! array.  For example, consider the following document:
5//!
6//! ```json
7//! {
8//!   "foo": {
9//!     "bar": [
10//!       {"baz": 1},
11//!       {"baz": 2},
12//!       {"baz": 3},
13//!     ]
14//!   }
15//! }
16//! ```
17//!
18//! The pathspec `/foo/bar/*/baz` would reference the `baz` field of all three array entries in the
19//! `bar` array.  It is an error to use `*` to reference a field that is not an array.  It is an
20//! error to use `*` at the end of a path, e.g., `/foo/*`.
21//!
22//! Additionally, this crate will auto-create parent paths for the AddOperation only, e.g., the
23//! result of applying `AddOperation{ path: "/foo/bar", value: 1 }` to the empty document will be
24//!
25//! ```json
26//! { "foo": {"bar": 1}}
27//! ```
28
29mod errors;
30mod macros;
31
32use json_patch::patch;
33// mark these as re-exports in the generated docs (maybe related to
34// https://github.com/rust-lang/rust/issues/131180?)
35#[doc(no_inline)]
36pub use json_patch::{
37    AddOperation,
38    CopyOperation,
39    MoveOperation,
40    Patch,
41    PatchOperation,
42    RemoveOperation,
43    ReplaceOperation,
44    TestOperation,
45};
46#[doc(no_inline)]
47pub use jsonptr::index::Index;
48pub use jsonptr::{
49    Pointer,
50    PointerBuf,
51    Token,
52};
53use serde_json::{
54    Value,
55    json,
56};
57
58pub use crate::errors::PatchError;
59
60pub mod prelude {
61    pub use super::{
62        AddOperation,
63        CopyOperation,
64        MoveOperation,
65        Patch,
66        PatchError,
67        PatchOperation,
68        Pointer,
69        PointerBuf,
70        RemoveOperation,
71        ReplaceOperation,
72        TestOperation,
73        Token,
74        add_operation,
75        copy_operation,
76        escape,
77        format_ptr,
78        matches,
79        move_operation,
80        patch_ext,
81        remove_operation,
82        replace_operation,
83        test_operation,
84    };
85}
86
87// PatchMode controls what to do if the referenced element does not exist in the object.
88#[derive(Debug, Clone, Copy)]
89enum PatchMode {
90    Error,
91    Create,
92    Skip,
93}
94
95pub fn add_operation(path: PointerBuf, value: Value) -> PatchOperation {
96    PatchOperation::Add(AddOperation { path, value })
97}
98
99pub fn copy_operation(from: PointerBuf, path: PointerBuf) -> PatchOperation {
100    PatchOperation::Copy(CopyOperation { from, path })
101}
102
103pub fn move_operation(from: PointerBuf, path: PointerBuf) -> PatchOperation {
104    PatchOperation::Move(MoveOperation { from, path })
105}
106
107pub fn remove_operation(path: PointerBuf) -> PatchOperation {
108    PatchOperation::Remove(RemoveOperation { path })
109}
110
111pub fn replace_operation(path: PointerBuf, value: Value) -> PatchOperation {
112    PatchOperation::Replace(ReplaceOperation { path, value })
113}
114
115pub fn test_operation(path: PointerBuf, value: Value) -> PatchOperation {
116    PatchOperation::Test(TestOperation { path, value })
117}
118
119pub fn escape(input: &str) -> String {
120    Token::new(input).encoded().into()
121}
122
123pub fn matches<'a>(path: &Pointer, value: &'a Value) -> Vec<(PointerBuf, &'a Value)> {
124    let Some(idx) = path.as_str().find("/*") else {
125        // Base case -- no stars;
126        // If we can't resolve, there's no match to be found
127        if let Ok(v) = path.resolve(value) {
128            return vec![(path.to_buf(), v)];
129        } else {
130            return vec![];
131        }
132    };
133
134    // we checked the index above so unwrap is safe here
135    let (head, cons) = path.split_at(idx).unwrap();
136    let mut res = vec![];
137
138    // If we can't resolve the head, or it's not an array, no match found
139    let Ok(head_val) = head.resolve(value) else {
140        return vec![];
141    };
142    let Some(next_array_val) = head_val.as_array() else {
143        return vec![];
144    };
145
146    for (i, v) in next_array_val.iter().enumerate() {
147        // /1 is a valid pointer so the unwrap below is fine
148        let idx_str = format!("/{i}");
149        let idx_path = PointerBuf::parse(&idx_str).unwrap();
150
151        // The cons pointer either looks like /* or /*/something, so we need to split_front
152        // to get the array marker out, and either return the current path if there's nothing
153        // else, or recurse and concatenate the subpath(s) to the head
154        if let Some((_, c)) = cons.split_front() {
155            let subpaths = matches(c, v);
156            res.extend(subpaths.iter().map(|(p, v)| (head.concat(&idx_path.concat(p)), *v)));
157        } else {
158            unreachable!("cons can't be root");
159        }
160    }
161    res
162}
163
164pub fn patch_ext(obj: &mut Value, p: PatchOperation) -> Result<(), PatchError> {
165    match p {
166        PatchOperation::Add(op) => add_or_replace(obj, &op.path, &op.value, false)?,
167        PatchOperation::Remove(op) => remove(obj, &op.path)?,
168        PatchOperation::Replace(op) => add_or_replace(obj, &op.path, &op.value, true)?,
169        x => patch(obj, &[x])?,
170    }
171    Ok(())
172}
173
174fn add_or_replace(obj: &mut Value, path: &Pointer, value: &Value, replace: bool) -> Result<(), PatchError> {
175    let Some((subpath, tail)) = path.split_back() else {
176        return Ok(());
177    };
178
179    // "replace" requires that the path you're replacing already exist, therefore we set
180    // create_if_not_exists = !replace.  We don't want to skip missing elements.
181    let mode = if replace { PatchMode::Error } else { PatchMode::Create };
182    for v in patch_ext_helper(subpath, obj, mode)? {
183        match v {
184            Value::Object(map) => {
185                let key = tail.decoded().into();
186                if replace && !map.contains_key(&key) {
187                    return Err(PatchError::TargetDoesNotExist(path.to_string()));
188                }
189                map.insert(key, value.clone());
190            },
191            Value::Array(vec) => match tail.to_index()? {
192                Index::Num(idx) => {
193                    vec.get(idx).ok_or(PatchError::OutOfBounds(idx))?;
194                    if replace {
195                        vec[idx] = value.clone();
196                    } else {
197                        vec.insert(idx, value.clone());
198                    }
199                },
200                Index::Next => {
201                    vec.push(value.clone());
202                },
203            },
204            _ => {
205                return Err(PatchError::UnexpectedType(path.to_string()));
206            },
207        }
208    }
209
210    Ok(())
211}
212
213fn remove(obj: &mut Value, path: &Pointer) -> Result<(), PatchError> {
214    let Some((subpath, key)) = path.split_back() else {
215        *obj = Value::Null;
216        return Ok(());
217    };
218
219    for v in patch_ext_helper(subpath, obj, PatchMode::Skip)? {
220        match v {
221            Value::Object(map) => {
222                map.remove(key.decoded().as_ref());
223            },
224            Value::Array(vec) => {
225                if key.decoded() == "*" {
226                    vec.clear();
227                } else if let Index::Num(idx) = key.to_index()? {
228                    vec.get(idx).ok_or(PatchError::OutOfBounds(idx))?;
229                    vec.remove(idx);
230                } else {
231                    return Err(PatchError::UnexpectedType(key.to_string()));
232                }
233            },
234            _ => {
235                return Err(PatchError::UnexpectedType(path.to_string()));
236            },
237        }
238    }
239
240    Ok(())
241}
242
243// Given JSON pointer, recursively walk through all the possible "end" values that the path
244// references; return a mutable reference so we can make modifications at those points.
245fn patch_ext_helper<'a>(
246    path: &Pointer,
247    value: &'a mut Value,
248    mode: PatchMode,
249) -> Result<Vec<&'a mut Value>, PatchError> {
250    let Some(idx) = path.as_str().find("/*") else {
251        if path.resolve(value).is_err() {
252            match mode {
253                PatchMode::Error => return Err(PatchError::TargetDoesNotExist(path.as_str().into())),
254                PatchMode::Create => {
255                    path.assign(value, json!({}))?;
256                },
257                PatchMode::Skip => return Ok(vec![]),
258            }
259        }
260        return Ok(vec![path.resolve_mut(value)?]);
261    };
262
263    // we checked the index above so unwrap is safe here
264    let (head, cons) = path.split_at(idx).unwrap();
265    let mut res = vec![];
266
267    // This is a little weird; if mode == Create, and the subpath up to this point doesn't exist,
268    // we'll create an empty array which we won't iterate over at all.  I think that's
269    // "approximately" fine and less surprising that not creating anything.
270    if head.resolve(value).is_err() {
271        match mode {
272            PatchMode::Error => return Err(PatchError::TargetDoesNotExist(path.as_str().into())),
273            PatchMode::Create => {
274                path.assign(value, json!([]))?;
275            },
276            PatchMode::Skip => return Ok(vec![]),
277        }
278    }
279
280    // Head now points at what we believe is an array; if not, it's an error.
281    let next_array_val =
282        head.resolve_mut(value)?.as_array_mut().ok_or(PatchError::UnexpectedType(head.as_str().into()))?;
283
284    // Iterate over all the array values and recurse, returning all found values
285    for v in next_array_val {
286        // The cons pointer either looks like /* or /*/something, so we need to split_front
287        // to get the array marker out, and either return the current value if there's nothing
288        // else, or recurse and return all the found values
289        if let Some((_, c)) = cons.split_front() {
290            res.extend(patch_ext_helper(c, v, mode)?);
291        } else {
292            unreachable!("cons can't be root");
293        }
294    }
295    Ok(res)
296}
297
298#[cfg(test)]
299mod tests {
300    use assertables::*;
301    use rstest::*;
302
303    use super::*;
304    use crate as json_patch_ext; // make the macros work in the tests
305
306    #[fixture]
307    fn data() -> Value {
308        json!({
309            "foo": [
310                {"baz": {"buzz": 0}},
311                {"baz": {"quzz": 1}},
312                {"baz": {"fixx": 2}},
313            ],
314        })
315    }
316
317    #[rstest]
318    fn test_matches_1(data: Value) {
319        let path = format_ptr!("/foo");
320        let m: Vec<_> = matches(&path, &data).iter().map(|(p, _)| p.clone()).collect();
321        assert_eq!(m, vec![format_ptr!("/foo")]);
322    }
323
324    #[rstest]
325    fn test_matches_2(data: Value) {
326        let path = format_ptr!("/foo/*/baz");
327        let m: Vec<_> = matches(&path, &data).iter().map(|(p, _)| p.clone()).collect();
328        assert_eq!(m, vec![format_ptr!("/foo/0/baz"), format_ptr!("/foo/1/baz"), format_ptr!("/foo/2/baz")]);
329    }
330
331    #[rstest]
332    fn test_matches_3(data: Value) {
333        let path = format_ptr!("/foo/*");
334        let m: Vec<_> = matches(&path, &data).iter().map(|(p, _)| p.clone()).collect();
335        assert_eq!(m, vec![format_ptr!("/foo/0"), format_ptr!("/foo/1"), format_ptr!("/foo/2")]);
336    }
337
338    #[rstest]
339    #[case(format_ptr!("/foo/*/baz/fixx"))]
340    #[case(format_ptr!("/foo/2/baz/fixx"))]
341    fn test_matches_4(#[case] path: PointerBuf, data: Value) {
342        let m: Vec<_> = matches(&path, &data).iter().map(|(p, _)| p.clone()).collect();
343        assert_eq!(m, vec![format_ptr!("/foo/2/baz/fixx")]);
344    }
345
346    #[rstest]
347    fn test_matches_root() {
348        let path = format_ptr!("/*");
349        let data = json!(["foo", "bar"]);
350        let m: Vec<_> = matches(&path, &data).iter().map(|(p, _)| p.clone()).collect();
351        assert_eq!(m, vec![format_ptr!("/0"), format_ptr!("/1")]);
352    }
353
354    #[rstest]
355    #[case(format_ptr!("/*"))]
356    #[case(format_ptr!("/food"))]
357    #[case(format_ptr!("/foo/3/baz"))]
358    #[case(format_ptr!("/foo/bar/baz"))]
359    #[case(format_ptr!("/foo/0/baz/fixx"))]
360    fn test_no_match(#[case] path: PointerBuf, data: Value) {
361        let m = matches(&path, &data);
362        assert_is_empty!(m);
363    }
364
365    #[rstest]
366    fn test_patch_ext_add(mut data: Value) {
367        let path = format_ptr!("/foo/*/baz/buzz");
368        let res = patch_ext(&mut data, add_operation(path, json!(42)));
369        assert_ok!(res);
370        assert_eq!(
371            data,
372            json!({
373                "foo": [
374                    {"baz": {"buzz": 42 }},
375                    {"baz": {"quzz": 1, "buzz": 42}},
376                    {"baz": {"fixx": 2, "buzz": 42}},
377                ],
378            })
379        );
380    }
381
382    #[rstest]
383    fn test_patch_ext_add_vec1(mut data: Value) {
384        let path = format_ptr!("/foo/1");
385        let res = patch_ext(&mut data, add_operation(path, json!(42)));
386        assert_ok!(res);
387        assert_eq!(
388            data,
389            json!({
390                "foo": [
391                    {"baz": {"buzz": 0}},
392                    42,
393                    {"baz": {"quzz": 1}},
394                    {"baz": {"fixx": 2}},
395                ],
396            })
397        );
398    }
399
400    #[rstest]
401    fn test_patch_ext_add_vec2(mut data: Value) {
402        let path = format_ptr!("/foo/-");
403        let res = patch_ext(&mut data, add_operation(path, json!(42)));
404        assert_ok!(res);
405        assert_eq!(
406            data,
407            json!({
408                "foo": [
409                    {"baz": {"buzz": 0}},
410                    {"baz": {"quzz": 1}},
411                    {"baz": {"fixx": 2}},
412                    42,
413                ],
414            })
415        );
416    }
417
418    #[rstest]
419    fn test_patch_ext_add_vec_err(mut data: Value) {
420        let path = format_ptr!("/foo/a");
421        let res = patch_ext(&mut data, add_operation(path, json!(42)));
422        assert_err!(res);
423    }
424
425    #[rstest]
426    fn test_patch_ext_add_escaped() {
427        let path = format_ptr!("/foo/bar/{}", escape("testing.sh/baz"));
428        let mut data = json!({});
429        let res = patch_ext(&mut data, add_operation(path, json!(42)));
430        assert_ok!(res);
431        assert_eq!(data, json!({"foo": {"bar": {"testing.sh/baz": 42}}}));
432    }
433
434    #[rstest]
435    fn test_patch_ext_replace(mut data: Value) {
436        let path = format_ptr!("/foo/*/baz");
437        let res = patch_ext(&mut data, replace_operation(path, json!(42)));
438        assert_ok!(res);
439        assert_eq!(
440            data,
441            json!({
442                "foo": [
443                    {"baz": 42},
444                    {"baz": 42},
445                    {"baz": 42},
446                ],
447            })
448        );
449    }
450
451    #[rstest]
452    fn test_patch_ext_replace_vec1(mut data: Value) {
453        let path = format_ptr!("/foo/1");
454        let res = patch_ext(&mut data, replace_operation(path, json!(42)));
455        assert_ok!(res);
456        assert_eq!(
457            data,
458            json!({
459                "foo": [
460                    {"baz": {"buzz": 0}},
461                    42,
462                    {"baz": {"fixx": 2}},
463                ],
464            })
465        );
466    }
467
468    #[rstest]
469    fn test_patch_ext_replace_vec2(mut data: Value) {
470        let path = format_ptr!("/foo/-");
471        let res = patch_ext(&mut data, replace_operation(path, json!(42)));
472        assert_ok!(res);
473        assert_eq!(
474            data,
475            json!({
476                "foo": [
477                    {"baz": {"buzz": 0}},
478                    {"baz": {"quzz": 1}},
479                    {"baz": {"fixx": 2}},
480                    42,
481                ],
482            })
483        );
484    }
485
486    #[rstest]
487    fn test_patch_ext_replace_err(mut data: Value) {
488        let path = format_ptr!("/foo/*/baz/buzz");
489        let res = patch_ext(&mut data, replace_operation(path, json!(42)));
490        assert_err!(res);
491    }
492
493    #[rstest]
494    fn test_patch_ext_remove_root(mut data: Value) {
495        let path = format_ptr!("");
496        let res = patch_ext(&mut data, remove_operation(path));
497        assert_ok!(res);
498        assert_eq!(data, json!(null));
499    }
500
501    #[rstest]
502    fn test_patch_ext_remove(mut data: Value) {
503        let path = format_ptr!("/foo/*/baz/quzz");
504        let res = patch_ext(&mut data, remove_operation(path));
505        assert_ok!(res);
506        assert_eq!(
507            data,
508            json!({
509                "foo": [
510                    {"baz": {"buzz": 0}},
511                    {"baz": {}},
512                    {"baz": {"fixx": 2}},
513                ],
514            })
515        );
516    }
517
518    #[rstest]
519    fn test_patch_ext_remove_wildcard(mut data: Value) {
520        let path = format_ptr!("/foo/*");
521        let res = patch_ext(&mut data, remove_operation(path));
522        assert_ok!(res);
523        assert_eq!(data, json!({"foo": []}));
524    }
525
526    #[rstest]
527    fn test_patch_ext_remove_nested_wildcards() {
528        let mut data = json!([[
529            [{"bar": "baz"}, {"qwerty": "yuiop"}],
530            [{"fuzz": "quzz"}],
531            [{"asdf": "hjkl"}],
532        ]]);
533        let path = format_ptr!("/*/*/*");
534        let res = patch_ext(&mut data, remove_operation(path));
535        assert_ok!(res);
536        assert_eq!(data, json!([[[], [], []]]));
537    }
538
539    #[rstest]
540    fn test_patch_ext_remove_vec(mut data: Value) {
541        let path = format_ptr!("/foo/1");
542        let res = patch_ext(&mut data, remove_operation(path));
543        assert_ok!(res);
544        assert_eq!(
545            data,
546            json!({
547                "foo": [
548                    {"baz": {"buzz": 0}},
549                    {"baz": {"fixx": 2}},
550                ],
551            })
552        );
553    }
554
555    #[rstest]
556    fn test_patch_ext_remove_vec_err(mut data: Value) {
557        let path = format_ptr!("/foo/-");
558        let res = patch_ext(&mut data, remove_operation(path));
559        assert_err!(res);
560    }
561}