Skip to main content

JsonPath

Struct JsonPath 

Source
pub struct JsonPath { /* private fields */ }
Expand description

Type-safe JSON path for addressing nodes in JSON structures.

Represented as a sequence of PathSegments; the root path ($) is the empty sequence. Every constructor funnels object keys through the same validation rule (see validate_key), so a JsonPath can never contain a key that would make Display/FromStr ambiguous — see the invariant documented on JsonPath’s Display impl (JP-1).

Implementations§

Source§

impl JsonPath

Source

pub fn root() -> JsonPath

Create the root path ($), i.e. the empty segment sequence.

Source

pub fn new(path: impl Into<String>) -> Result<JsonPath, DomainError>

Parse a JSON path from its textual form (e.g. "$.users[0].name").

§Examples
use pjson_rs_domain::value_objects::JsonPath;

let path = JsonPath::new("$.users[0].name").unwrap();
assert_eq!(path.depth(), 3);
assert_eq!(path.to_string(), "$.users[0].name");

assert!(JsonPath::new("$.key[not_a_number]").is_err());
Source

pub fn from_segments( segments: impl IntoIterator<Item = PathSegment>, ) -> Result<JsonPath, DomainError>

Build a path directly from segments, validating every PathSegment::Key with the same rule as JsonPath::append_key.

§Examples
use pjson_rs_domain::value_objects::{JsonPath, PathSegment};

let path = JsonPath::from_segments(vec![
    PathSegment::Key("users".to_string()),
    PathSegment::Index(0),
])
.unwrap();
assert_eq!(path.to_string(), "$.users[0]");

// A key containing a delimiter is rejected, just like `append_key`.
let invalid = JsonPath::from_segments(vec![PathSegment::Key("a.b".to_string())]);
assert!(invalid.is_err());
Source

pub fn append_key(&self, key: &str) -> Result<JsonPath, DomainError>

Append a key segment, producing a new path.

§Examples
use pjson_rs_domain::value_objects::JsonPath;

let path = JsonPath::root().append_key("users").unwrap();
assert_eq!(path.to_string(), "$.users");

// Keys containing '.', '[', ']', or the empty key are rejected.
assert!(JsonPath::root().append_key("").is_err());
assert!(JsonPath::root().append_key("a.b").is_err());
Source

pub fn append_index(&self, index: usize) -> JsonPath

Append an array index segment, producing a new path.

Source

pub fn segments(&self) -> &[PathSegment]

Borrow the path’s segments.

Source

pub fn depth(&self) -> usize

Number of segments in the path (0 for root).

Source

pub fn parent(&self) -> Option<JsonPath>

Get the parent path, or None if this is the root.

O(1) on the segmented representation. This corrects a bug in the previous string-based implementation, which returned root for any path ending in an index segment following a key (e.g. $.users[0] incorrectly produced $ instead of $.users).

Source

pub fn last_segment(&self) -> Option<&PathSegment>

Get the last segment of the path, or None at root.

Distinct from JsonPath::last_key: this returns the literal final segment, whether it is a key or an index.

Source

pub fn last_key(&self) -> Option<&str>

Get the last Key segment, skipping any trailing Index segments.

Distinct from JsonPath::last_segment: for $.arr[5] this returns Some("arr"), not None. Preserves the WASM/HTTP priority-heuristic parity fixed in #242 — do not conflate the two methods.

Source

pub fn is_prefix_of(&self, other: &JsonPath) -> bool

Check whether self is a strict prefix of other (self-prefix is false).

Source

pub fn to_json_pointer(&self) -> String

Convert to a JSON Pointer (RFC 6901) string.

Does not escape ~ or / within keys; see follow-up issue for #379.

§Examples
use pjson_rs_domain::value_objects::JsonPath;

let path = JsonPath::new("$.users[0].name").unwrap();
assert_eq!(path.to_json_pointer(), "/users/0/name");
assert_eq!(JsonPath::root().to_json_pointer(), "/");

Trait Implementations§

Source§

impl Clone for JsonPath

Source§

fn clone(&self) -> JsonPath

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for JsonPath

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for JsonPath

Source§

fn deserialize<D>( deserializer: D, ) -> Result<JsonPath, <D as Deserializer<'de>>::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for JsonPath

INVARIANT (JP-1): Display is injective and total over representable JsonPath values. It holds only because key validation (validate_key) excludes ., [, ], and the empty key: those delimiters cannot occur inside a valid key, so the boundary between a key and the next segment marker is always unambiguous, and every rendered path re-parses via FromStr to the same segments. Any future change that widens the key alphabet to admit ., [, ], or the empty string must add an escaping grammar (e.g. bracket-quote form with backslash-escaping) and a round-trip proptest in the same change, or Display/FromStr become a path-forgery primitive (see issue #333).

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Eq for JsonPath

Source§

impl FromStr for JsonPath

Parses the textual form produced by JsonPath’s Display impl. See the injectivity/totality invariant documented there (JP-1).

Source§

type Err = DomainError

The associated error which can be returned from parsing.
Source§

fn from_str(path: &str) -> Result<JsonPath, <JsonPath as FromStr>::Err>

Parses a string s to return a value of this type. Read more
Source§

impl Hash for JsonPath

Source§

fn hash<__H>(&self, state: &mut __H)
where __H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for JsonPath

Source§

fn eq(&self, other: &JsonPath) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for JsonPath

Source§

fn serialize<S>( &self, serializer: S, ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for JsonPath

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more