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
//! Types for representing [Normalized Paths][norm-paths] from the JSONPath specification
//!
//! [norm-paths]: https://www.rfc-editor.org/rfc/rfc9535.html#name-normalized-paths
use std::{
cmp::Ordering,
fmt::Display,
slice::{Iter, SliceIndex},
};
use serde::Serialize;
// Documented in the serde_json_path crate, for linking purposes
#[allow(missing_docs)]
#[derive(Debug, Default, Eq, PartialEq, Clone, PartialOrd)]
pub struct NormalizedPath<'a>(Vec<PathElement<'a>>);
impl<'a> NormalizedPath<'a> {
pub(crate) fn push<T: Into<PathElement<'a>>>(&mut self, elem: T) {
self.0.push(elem.into())
}
pub(crate) fn clone_and_push<T: Into<PathElement<'a>>>(&self, elem: T) -> Self {
let mut new_path = self.clone();
new_path.push(elem.into());
new_path
}
/// Get the [`NormalizedPath`] as a [JSON Pointer][json-pointer] string
///
/// This can be used with the [`serde_json::Value::pointer`] or
/// [`serde_json::Value::pointer_mut`] methods.
///
/// # Example
/// ```rust
/// # use serde_json::json;
/// # use serde_json_path::JsonPath;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut value = json!({"foo": ["bar", "baz"]});
/// let path = JsonPath::parse("$.foo[? @ == 'bar']")?;
/// let pointer= path
/// .query_located(&value)
/// .exactly_one()?
/// .location()
/// .to_json_pointer();
/// *value.pointer_mut(&pointer).unwrap() = "bop".into();
/// assert_eq!(value, json!({"foo": ["bop", "baz"]}));
/// # Ok(())
/// # }
/// ```
///
/// [json-pointer]: https://datatracker.ietf.org/doc/html/rfc6901
pub fn to_json_pointer(&self) -> String {
self.0
.iter()
.map(PathElement::to_json_pointer)
.fold(String::from(""), |mut acc, s| {
acc.push('/');
acc.push_str(&s);
acc
})
}
/// Check if the [`NormalizedPath`] is empty
///
/// An empty normalized path represents the location of the root node of the JSON object,
/// i.e., `$`.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Get the length of the [`NormalizedPath`]
pub fn len(&self) -> usize {
self.0.len()
}
/// Get an iterator over the [`PathElement`]s of the [`NormalizedPath`]
///
/// Note that [`NormalizedPath`] also implements [`IntoIterator`]
///
/// # Example
/// ```rust
/// # use serde_json::json;
/// # use serde_json_path::JsonPath;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut value = json!({"foo": {"bar": 1, "baz": 2, "bop": 3}});
/// let path = JsonPath::parse("$.foo[? @ == 2]")?;
/// let location = path.query_located(&value).exactly_one()?.to_location();
/// let elements: Vec<String> = location
/// .iter()
/// .map(|ele| ele.to_string())
/// .collect();
/// assert_eq!(elements, ["foo", "baz"]);
/// # Ok(())
/// # }
/// ```
pub fn iter(&self) -> Iter<'_, PathElement<'a>> {
self.0.iter()
}
/// Get the [`PathElement`] at `index`, or `None` if the index is out of bounds
///
/// # Example
/// ```rust
/// # use serde_json::json;
/// # use serde_json_path::JsonPath;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let value = json!({"foo": {"bar": {"baz": "bop"}}});
/// let path = JsonPath::parse("$..baz")?;
/// let location = path.query_located(&value).exactly_one()?.to_location();
/// assert_eq!(location.to_string(), "$['foo']['bar']['baz']");
/// assert!(location.get(0).is_some_and(|p| p == "foo"));
/// assert!(location.get(1..).is_some_and(|p| p == ["bar", "baz"]));
/// assert!(location.get(3).is_none());
/// # Ok(())
/// # }
/// ```
pub fn get<I>(&self, index: I) -> Option<&I::Output>
where
I: SliceIndex<[PathElement<'a>]>,
{
self.0.get(index)
}
/// Get the first [`PathElement`], or `None` if the path is empty
///
/// # Example
/// ```rust
/// # use serde_json::json;
/// # use serde_json_path::JsonPath;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let value = json!(["foo", true, {"bar": false}, {"bar": true}]);
/// let path = JsonPath::parse("$..[? @ == false]")?;
/// let location = path.query_located(&value).exactly_one()?.to_location();
/// assert_eq!(location.to_string(), "$[2]['bar']");
/// assert!(location.first().is_some_and(|p| *p == 2));
/// # Ok(())
/// # }
/// ```
pub fn first(&self) -> Option<&PathElement<'a>> {
self.0.first()
}
/// Get the last [`PathElement`], or `None` if the path is empty
///
/// # Example
/// ```rust
/// # use serde_json::json;
/// # use serde_json_path::JsonPath;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let value = json!({"foo": {"bar": [1, 2, 3]}});
/// let path = JsonPath::parse("$..[? @ == 2]")?;
/// let location = path.query_located(&value).exactly_one()?.to_location();
/// assert_eq!(location.to_string(), "$['foo']['bar'][1]");
/// assert!(location.last().is_some_and(|p| *p == 1));
/// # Ok(())
/// # }
/// ```
pub fn last(&self) -> Option<&PathElement<'a>> {
self.0.last()
}
}
impl<'a> IntoIterator for NormalizedPath<'a> {
type Item = PathElement<'a>;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl<'a> Display for NormalizedPath<'a> {
/// Format the [`NormalizedPath`] as a JSONPath string using the canonical bracket notation
/// as per the [JSONPath Specification][norm-paths]
///
/// # Example
/// ```rust
/// # use serde_json::json;
/// # use serde_json_path::JsonPath;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let value = json!({"foo": ["bar", "baz"]});
/// let path = JsonPath::parse("$.foo[0]")?;
/// let location = path.query_located(&value).exactly_one()?.to_location();
/// assert_eq!(location.to_string(), "$['foo'][0]");
/// # Ok(())
/// # }
/// ```
///
/// [norm-paths]: https://www.rfc-editor.org/rfc/rfc9535.html#name-normalized-paths
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "$")?;
for elem in &self.0 {
match elem {
PathElement::Name(name) => write!(f, "['{name}']")?,
PathElement::Index(index) => write!(f, "[{index}]")?,
}
}
Ok(())
}
}
impl<'a> Serialize for NormalizedPath<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.to_string().as_str())
}
}
/// An element within a [`NormalizedPath`]
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum PathElement<'a> {
/// A key within a JSON object
Name(&'a str),
/// An index of a JSON Array
Index(usize),
}
impl<'a> PathElement<'a> {
fn to_json_pointer(&self) -> String {
match self {
PathElement::Name(s) => s.replace('~', "~0").replace('/', "~1"),
PathElement::Index(i) => i.to_string(),
}
}
/// Get the underlying name if the [`PathElement`] is `Name`, or `None` otherwise
pub fn as_name(&self) -> Option<&str> {
match self {
PathElement::Name(n) => Some(n),
PathElement::Index(_) => None,
}
}
/// Get the underlying index if the [`PathElement`] is `Index`, or `None` otherwise
pub fn as_index(&self) -> Option<usize> {
match self {
PathElement::Name(_) => None,
PathElement::Index(i) => Some(*i),
}
}
/// Test if the [`PathElement`] is `Name`
pub fn is_name(&self) -> bool {
self.as_name().is_some()
}
/// Test if the [`PathElement`] is `Index`
pub fn is_index(&self) -> bool {
self.as_index().is_some()
}
}
impl<'a> PartialOrd for PathElement<'a> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match (self, other) {
(PathElement::Name(a), PathElement::Name(b)) => a.partial_cmp(b),
(PathElement::Index(a), PathElement::Index(b)) => a.partial_cmp(b),
_ => None,
}
}
}
impl<'a> PartialEq<str> for PathElement<'a> {
fn eq(&self, other: &str) -> bool {
match self {
PathElement::Name(s) => s.eq(&other),
PathElement::Index(_) => false,
}
}
}
impl<'a> PartialEq<&str> for PathElement<'a> {
fn eq(&self, other: &&str) -> bool {
match self {
PathElement::Name(s) => s.eq(other),
PathElement::Index(_) => false,
}
}
}
impl<'a> PartialEq<usize> for PathElement<'a> {
fn eq(&self, other: &usize) -> bool {
match self {
PathElement::Name(_) => false,
PathElement::Index(i) => i.eq(other),
}
}
}
impl<'a> Display for PathElement<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PathElement::Name(n) => write!(f, "{n}"),
PathElement::Index(i) => write!(f, "{i}"),
}
}
}
impl<'a> From<&'a String> for PathElement<'a> {
fn from(s: &'a String) -> Self {
Self::Name(s.as_str())
}
}
impl<'a> From<usize> for PathElement<'a> {
fn from(index: usize) -> Self {
Self::Index(index)
}
}
impl<'a> Serialize for PathElement<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
PathElement::Name(s) => serializer.serialize_str(s),
PathElement::Index(i) => serializer.serialize_u64(*i as u64),
}
}
}
#[cfg(test)]
mod tests {
use super::{NormalizedPath, PathElement};
#[test]
fn normalized_path_to_json_pointer() {
let np = NormalizedPath(vec![
PathElement::Name("foo"),
PathElement::Index(42),
PathElement::Name("bar"),
]);
assert_eq!(np.to_json_pointer(), "/foo/42/bar");
}
#[test]
fn normalized_path_to_json_pointer_with_escapes() {
let np = NormalizedPath(vec![
PathElement::Name("foo~bar"),
PathElement::Index(42),
PathElement::Name("baz/bop"),
]);
assert_eq!(np.to_json_pointer(), "/foo~0bar/42/baz~1bop");
}
}