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
//! Implementation of the `JSONPath` spec, Proposal A with extensions.

#![forbid(unsafe_code)]
#![warn(
    missing_docs,
    elided_lifetimes_in_paths,
    explicit_outlives_requirements,
    missing_abi,
    noop_method_call,
    pointer_structural_match,
    semicolon_in_expressions_from_macros,
    unused_import_braces,
    unused_lifetimes,
    clippy::cargo,
    clippy::missing_panics_doc,
    clippy::doc_markdown,
    clippy::ptr_as_ptr,
    clippy::cloned_instead_of_copied,
    clippy::unreadable_literal,
    clippy::must_use_candidate
)]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]

use serde_json::Value;

use error::{ParseError, ParseOrJsonError};
use eval::EvalCtx;
use idx::{Idx, IdxPath};
use utils::{delete_paths, replace_paths, try_replace_paths};

pub mod ast;
pub mod error;
mod eval;
pub mod idx;
mod utils;

#[doc(inline)]
pub use ast::Path as JsonPath;

/// Find a pattern in the provided JSON value. Recompiles the pattern every call, if the same
/// pattern is used a lot should instead try using [`JsonPath::compile`].
///
/// # Errors
///
/// - If the provided pattern fails to parse as a valid JSON path
pub fn find<'a>(pattern: &str, value: &'a Value) -> Result<Vec<&'a Value>, ParseError> {
    Ok(JsonPath::compile(pattern)?.find(value))
}

/// Find a pattern in the provided JSON string. Recompiles the pattern every call, if the same
/// pattern is used a lot should instead try using [`JsonPath::compile`].
///
/// # Errors
///
/// - If the provided pattern fails to parse as a valid JSON path
/// - If the provided value fails to deserialize
pub fn find_str(pattern: &str, value: &str) -> Result<Vec<Value>, ParseOrJsonError> {
    Ok(JsonPath::compile(pattern)?.find_str(value)?)
}

impl JsonPath {
    /// Compile a JSON path, which can be used to match items multiple times.
    ///
    /// # Errors
    ///
    /// - If the provided pattern fails to parse as a valid JSON path
    pub fn compile(pattern: &str) -> Result<JsonPath, ParseError> {
        use chumsky::Parser;

        Self::parser()
            .parse(pattern)
            .map_err(|e| ParseError::new(pattern, e))
    }

    /// Find this pattern in the provided JSON value
    #[must_use = "this does not modify the path or provided value"]
    pub fn find<'a>(&self, value: &'a Value) -> Vec<&'a Value> {
        let mut ctx = EvalCtx::new(value);
        self.eval(&mut ctx);
        ctx.into_matched()
    }

    /// Find this pattern in the provided JSON value, and return the shortest paths to all found
    /// values as a chain of indices
    #[must_use = "this does not modify the path or provided value"]
    pub fn find_paths(&self, value: &Value) -> Vec<IdxPath> {
        let mut ctx = EvalCtx::new(value);
        self.eval(&mut ctx);
        ctx.paths_matched()
    }

    /// Delete all items matched by this pattern on the provided JSON value, and return the
    /// resulting object
    #[must_use = "this returns the new value, without modifying the original. To work in-place, \
                  use `delete_on`"]
    pub fn delete(&self, value: &Value) -> Value {
        let paths = self.find_paths(value);
        let mut out = value.clone();
        delete_paths(paths, &mut out);
        out
    }

    /// Delete all items matched by this pattern on the provided JSON value, operating in-place
    pub fn delete_on(&self, value: &mut Value) {
        let paths = self.find_paths(value);
        delete_paths(paths, value);
    }

    /// Replace items matched by this pattern on the provided JSON value, filling them with the
    /// value returned by the provided function, then return the resulting object
    #[must_use = "this returns the new value, without modifying the original. To work in-place, \
                  use `replace_on`"]
    pub fn replace(&self, value: &Value, f: impl FnMut(&Value) -> Value) -> Value {
        let paths = self.find_paths(value);
        let mut out = value.clone();
        replace_paths(paths, &mut out, f);
        out
    }

    /// Replace items matched by this pattern on the provided JSON value, filling them the value
    /// returned by the provided function, operating in-place
    pub fn replace_on(&self, value: &mut Value, f: impl FnMut(&Value) -> Value) {
        let paths = self.find_paths(value);
        replace_paths(paths, value, f);
    }

    /// Replace or delete items matched by this pattern on the provided JSON value. Replaces if the
    /// provided method returns `Some`, deletes if the provided method returns `None`. This method
    /// then returns the resulting object
    #[must_use = "this returns the new value, without modifying the original. To work in-place, \
                  use `try_replace_on`"]
    pub fn try_replace(&self, value: &Value, f: impl FnMut(&Value) -> Option<Value>) -> Value {
        let paths = self.find_paths(value);
        let mut out = value.clone();
        try_replace_paths(paths, &mut out, f);
        out
    }

    /// Replace or delete items matched by this pattern on the provided JSON value. Replaces if the
    /// provided method returns `Some`, deletes if the provided method returns `None`. This method
    /// operates in-place on the provided value
    pub fn try_replace_on(&self, value: &mut Value, f: impl FnMut(&Value) -> Option<Value>) {
        let paths = self.find_paths(value);
        try_replace_paths(paths, value, f);
    }

    /// Find this pattern in the provided JSON string
    ///
    /// # Errors
    ///
    /// - If the provided value fails to deserialize
    pub fn find_str(&self, str: &str) -> Result<Vec<Value>, serde_json::Error> {
        let val = serde_json::from_str(str)?;
        Ok(self.find(&val).into_iter().cloned().collect())
    }

    /// Delete items matching this pattern in the provided JSON string
    ///
    /// # Errors
    ///
    /// - If the provided value fails to deserialize
    pub fn delete_str(&self, str: &str) -> Result<Value, serde_json::Error> {
        let val = serde_json::from_str(str)?;
        Ok(self.delete(&val))
    }

    /// Replace items matching this pattern in the provided JSON string
    ///
    /// # Errors
    ///
    /// - If the provided value fails to deserialize
    pub fn replace_str(
        &self,
        str: &str,
        f: impl FnMut(&Value) -> Value,
    ) -> Result<Value, serde_json::Error> {
        let val = serde_json::from_str(str)?;
        Ok(self.replace(&val, f))
    }

    /// Replace or delete items matching this pattern in the provided JSON string
    ///
    /// # Errors
    ///
    /// - If the provided value fails to deserialize
    pub fn try_replace_str(
        &self,
        str: &str,
        f: impl FnMut(&Value) -> Option<Value>,
    ) -> Result<Value, serde_json::Error> {
        let val = serde_json::from_str(str)?;
        Ok(self.try_replace(&val, f))
    }
}

#[cfg(test)]
mod tests;