json_toolkit/
lib.rs

1//! # json-toolkit
2//!
3//! The `json-toolkit` crate exposes all the common manipulation/validation operation expected from a JSON pointer and support
4//! several JSON value representation :
5//! - Encode [RFC6901](https://datatracker.ietf.org/doc/html/rfc6901) representation in [`Pointer`](crate::pointer::Pointer) type.
6//! - Manipulate any JSON value by a JSON pointer.
7//!
8//! ```
9//! use json_toolkit::{ValueExt, Pointer};
10//! use serde_json::{Value, json};
11//!
12//! let mut json = json!({ "foo": "bar", "zoo": { "id": 1 } });
13//!
14//! json.insert_at(&Pointer::new("/zoo/new_field").unwrap(), "new_value").unwrap();
15//! assert_eq!(json, json!({ "foo": "bar", "zoo": { "id": 1, "new_field": "new_value" } }));
16//!
17//! let old_value = json.insert("foo".to_string(), 42).unwrap();
18//! assert_eq!(old_value, Some("bar".into()));
19//! assert_eq!(json, json!({ "foo": 42, "zoo": { "id": 1, "new_field": "new_value" } }));
20//!
21//! let id = ValueExt::pointer(&json, &Pointer::new("/zoo/id").unwrap());
22//! assert_eq!(id, Some(&1.into()));
23//! ```
24//!
25//! ## Features
26//!
27//! `json-toolkit` supports several JSON value representation, and has features that may be enabled or disabled :
28//! - `serde`: Enable [`serde`](https://docs.rs/serde/latest/serde/) {de}serialization on [`Pointer`](crate::pointer::Pointer) type
29//! and implement [`ValueExt`](crate::ValueExt) on [`serde_json::Value`](https://docs.rs/serde_json/latest/serde_json/enum.Value.html) type.
30//! - `json`: Implement [`ValueExt`](crate::ValueExt) on [`json::JsonValue`](https://docs.rs/json/latest/json/enum.JsonValue.html) type.
31
32mod error;
33#[cfg(feature = "json")]
34/// [`ValueExt`] implementation for [`json::Value`][::json::JsonValue] type.
35pub mod json;
36mod pointer;
37#[cfg(feature = "serde")]
38/// [`ValueExt`] implementation for [`serde_json::Value`] type.
39pub mod serde;
40
41pub use error::Error;
42pub use pointer::Pointer;
43
44/// An extension trait for any JSON value representation that provides a variety of manipulation methods.
45pub trait ValueExt: Sized {
46    /// Inserts any data at the given pointee JSON value.
47    ///
48    /// If the JSON pointer's key already exists in the JSON pointee value, it will be overrided.
49    ///
50    /// # Arguments
51    /// * `pointer`: A JSON pointer.
52    /// * `value`: A data to insert at the pointee JSON value.
53    ///
54    /// # Errors
55    /// This method may fail if the pointee JSON value is not a JSON object or if it does not exist.
56    fn insert_at(&mut self, pointer: &Pointer<'_>, value: impl Into<Self>) -> Result<Option<Self>, Error> {
57        let mut value = value.into();
58
59        if pointer.is_root() {
60            std::mem::swap(self, &mut value);
61
62            return Ok(Some(value));
63        }
64
65        // both `unwrap` calls are safe here since we checked earlier than the given pointer is not a root JSON pointer.
66        let parent_pointer = pointer.parent().unwrap();
67        let pointer_key = pointer.key().unwrap();
68
69        match self.pointer_mut(&parent_pointer) {
70            Some(pointee_value) => pointee_value.insert(pointer_key, value),
71            None => Err(Error::KeyNotFound),
72        }
73    }
74
75    /// Insert any data in the current JSON value.
76    ///
77    /// If the JSON value already contains the given key, it will be overrided.
78    ///
79    /// # Errors
80    /// This method may fail if the current JSON value is not a JSON object.
81    fn insert(&mut self, key: String, value: impl Into<Self>) -> Result<Option<Self>, Error>;
82
83    /// Looks up a value by a JSON pointer.
84    fn pointer(&self, pointer: &Pointer<'_>) -> Option<&Self>;
85
86    /// Looks up a value by a JSON pointer and returns a mutable reference to that value.
87    fn pointer_mut(&mut self, pointer: &Pointer<'_>) -> Option<&mut Self>;
88}