jsonpath/src/lib.rs

366 lines
11 KiB
Rust
Raw Normal View History

2019-03-06 23:50:10 +09:00
//! JsonPath implementation for Rust
2019-03-05 23:48:27 +09:00
//!
//! # Example
//! ```
2019-03-06 18:55:21 +09:00
//! extern crate jsonpath_lib as jsonpath;
2019-03-06 23:50:10 +09:00
//! #[macro_use] extern crate serde_json;
2019-03-05 23:48:27 +09:00
//!
2019-03-06 18:55:21 +09:00
//! let json_obj = json!({
2019-03-05 23:48:27 +09:00
//! "store": {
//! "book": [
//! {
//! "category": "reference",
//! "author": "Nigel Rees",
//! "title": "Sayings of the Century",
//! "price": 8.95
//! },
//! {
//! "category": "fiction",
//! "author": "Evelyn Waugh",
//! "title": "Sword of Honour",
//! "price": 12.99
//! },
//! {
//! "category": "fiction",
//! "author": "Herman Melville",
//! "title": "Moby Dick",
//! "isbn": "0-553-21311-3",
//! "price": 8.99
//! },
//! {
//! "category": "fiction",
//! "author": "J. R. R. Tolkien",
//! "title": "The Lord of the Rings",
//! "isbn": "0-395-19395-8",
//! "price": 22.99
//! }
//! ],
//! "bicycle": {
//! "color": "red",
//! "price": 19.95
//! }
//! },
//! "expensive": 10
2019-03-06 18:55:21 +09:00
//! });
2019-03-05 23:48:27 +09:00
//!
2019-03-14 22:30:42 +09:00
//! let mut selector = jsonpath::selector(&json_obj);
2019-03-05 23:48:27 +09:00
//!
2019-03-06 18:55:21 +09:00
//! //
//! // $.store.book[*].author
//! //
2019-03-11 17:35:15 +09:00
//! let json = selector("$.store.book[*].author").unwrap();
2019-03-06 18:55:21 +09:00
//! let ret = json!(["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]);
//! assert_eq!(json, ret);
2019-03-05 23:48:27 +09:00
//!
2019-03-06 18:55:21 +09:00
//! //
//! // $..author
//! //
2019-03-11 17:35:15 +09:00
//! let json = selector("$..author").unwrap();
2019-03-06 18:55:21 +09:00
//! let ret = json!(["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]);
//! assert_eq!(json, ret);
2019-03-05 23:48:27 +09:00
//!
2019-03-06 18:55:21 +09:00
//! //
//! // $.store.*
//! //
2019-03-11 17:35:15 +09:00
//! let json = selector("$.store.*").unwrap();
2019-03-06 18:55:21 +09:00
//! let ret = json!([
//! [
//! {"category" : "reference", "author" : "Nigel Rees","title" : "Sayings of the Century", "price" : 8.95},
//! {"category" : "fiction", "author" : "Evelyn Waugh","title" : "Sword of Honour","price" : 12.99},
//! {"category" : "fiction", "author" : "Herman Melville","title" : "Moby Dick","isbn" : "0-553-21311-3","price" : 8.99},
//! {"category" : "fiction", "author" : "J. R. R. Tolkien","title" : "The Lord of the Rings","isbn" : "0-395-19395-8","price" : 22.99}
//! ],
//! {"color" : "red","price" : 19.95},
//! ]);
//! assert_eq!(ret, json);
2019-03-05 23:48:27 +09:00
//!
2019-03-06 18:55:21 +09:00
//! //
//! // $.store..price
//! //
2019-03-11 17:35:15 +09:00
//! let json = selector("$.store..price").unwrap();
2019-03-06 18:55:21 +09:00
//! let ret = json!([8.95, 12.99, 8.99, 22.99, 19.95]);
//! assert_eq!(ret, json);
2019-03-05 23:48:27 +09:00
//!
2019-03-06 18:55:21 +09:00
//! //
//! // $..book[2]
//! //
2019-03-11 17:35:15 +09:00
//! let json = selector("$..book[2]").unwrap();
2019-03-06 18:55:21 +09:00
//! let ret = json!([{
//! "category" : "fiction",
//! "author" : "Herman Melville",
//! "title" : "Moby Dick",
//! "isbn" : "0-553-21311-3",
//! "price" : 8.99
//! }]);
//! assert_eq!(ret, json);
2019-03-05 23:48:27 +09:00
//!
2019-03-06 18:55:21 +09:00
//! //
//! // $..book[-2]
//! //
2019-03-11 17:35:15 +09:00
//! let json = selector("$..book[-2]").unwrap();
2019-03-06 18:55:21 +09:00
//! let ret = json!([{
//! "category" : "fiction",
//! "author" : "Herman Melville",
//! "title" : "Moby Dick",
//! "isbn" : "0-553-21311-3",
//! "price" : 8.99
//! }]);
//! assert_eq!(ret, json);
2019-03-05 23:48:27 +09:00
//!
2019-03-06 18:55:21 +09:00
//! //
//! // $..book[0,1]
//! //
2019-03-11 17:35:15 +09:00
//! let json = selector("$..book[0,1]").unwrap();
2019-03-06 18:55:21 +09:00
//! let ret = json!([
//! {"category" : "reference","author" : "Nigel Rees","title" : "Sayings of the Century","price" : 8.95},
//! {"category" : "fiction","author" : "Evelyn Waugh","title" : "Sword of Honour","price" : 12.99}
//! ]);
//! assert_eq!(ret, json);
2019-03-05 23:48:27 +09:00
//!
2019-03-06 18:55:21 +09:00
//! //
//! // $..book[:2]
//! //
2019-03-11 17:35:15 +09:00
//! let json = selector("$..book[:2]").unwrap();
2019-03-06 18:55:21 +09:00
//! let ret = json!([
//! {"category" : "reference","author" : "Nigel Rees","title" : "Sayings of the Century","price" : 8.95},
//! {"category" : "fiction","author" : "Evelyn Waugh","title" : "Sword of Honour","price" : 12.99}
//! ]);
//! assert_eq!(ret, json);
2019-03-05 23:48:27 +09:00
//!
2019-03-06 18:55:21 +09:00
//! //
//! // $..book[2:]
//! //
2019-03-11 17:35:15 +09:00
//! let json = selector("$..book[2:]").unwrap();
2019-03-06 18:55:21 +09:00
//! let ret = json!([
//! {"category" : "fiction","author" : "Herman Melville","title" : "Moby Dick","isbn" : "0-553-21311-3","price" : 8.99},
//! {"category" : "fiction","author" : "J. R. R. Tolkien","title" : "The Lord of the Rings","isbn" : "0-395-19395-8","price" : 22.99}
//! ]);
//! assert_eq!(ret, json);
2019-03-05 23:48:27 +09:00
//!
2019-03-06 18:55:21 +09:00
//! //
//! // $..book[?(@.isbn)]
//! //
2019-03-11 17:35:15 +09:00
//! let json = selector("$..book[?(@.isbn)]").unwrap();
2019-03-06 18:55:21 +09:00
//! let ret = json!([
//! {"category" : "fiction","author" : "Herman Melville","title" : "Moby Dick","isbn" : "0-553-21311-3","price" : 8.99},
//! {"category" : "fiction","author" : "J. R. R. Tolkien","title" : "The Lord of the Rings","isbn" : "0-395-19395-8","price" : 22.99}
//! ]);
//! assert_eq!(ret, json);
2019-03-05 23:48:27 +09:00
//!
2019-03-06 18:55:21 +09:00
//! //
//! // $.store.book[?(@.price < 10)]
//! //
2019-03-11 17:35:15 +09:00
//! let json = selector("$.store.book[?(@.price < 10)]").unwrap();
2019-03-06 18:55:21 +09:00
//! let ret = json!([
//! {"category" : "reference","author" : "Nigel Rees","title" : "Sayings of the Century","price" : 8.95},
//! {"category" : "fiction","author" : "Herman Melville","title" : "Moby Dick","isbn" : "0-553-21311-3","price" : 8.99}
//! ]);
//! assert_eq!(ret, json);
2019-03-05 23:48:27 +09:00
//! ```
2019-03-06 23:50:10 +09:00
extern crate indexmap;
2018-12-26 14:45:31 +09:00
#[macro_use]
extern crate log;
2019-03-24 21:18:58 +09:00
#[macro_use]
extern crate serde;
2019-03-05 18:43:58 +09:00
extern crate serde_json;
2019-03-24 21:18:58 +09:00
use std::ops::Deref;
use std::result;
use serde_json::Value;
2019-03-24 21:18:58 +09:00
use filter::value_filter::JsonValueFilter;
use parser::parser::{NodeVisitor, Parser};
use ref_value::model::{RefValue, RefValueWrapper};
2019-02-26 23:04:04 +09:00
2019-03-05 23:48:27 +09:00
#[doc(hidden)]
2019-03-24 21:18:58 +09:00
pub mod parser;
2019-03-05 23:48:27 +09:00
#[doc(hidden)]
2019-03-24 21:18:58 +09:00
pub mod filter;
2019-03-11 17:35:15 +09:00
#[doc(hidden)]
2019-03-24 21:18:58 +09:00
pub mod ref_value;
2019-02-26 23:04:04 +09:00
2019-03-24 21:18:58 +09:00
/// # Compile a Jsonpath so it select a JsonObject immediately.
2019-03-05 23:48:27 +09:00
///
/// ```rust
2019-03-06 23:50:10 +09:00
/// extern crate jsonpath_lib as jsonpath;
/// #[macro_use] extern crate serde_json;
///
2019-03-05 23:48:27 +09:00
/// let mut template = jsonpath::compile("$..friends[0]");
///
///
/// let json_obj = json!({
/// "school": {
/// "friends": [ {"id": 0}, {"id": 1} ]
/// },
/// "friends": [ {"id": 0}, {"id": 1} ]
/// });
///
2019-03-14 22:30:42 +09:00
/// let json = template(&json_obj).unwrap();
2019-03-05 23:48:27 +09:00
/// let ret = json!([ {"id": 0}, {"id": 0} ]);
/// assert_eq!(json, ret);
///
///
/// let json_obj = json!({
/// "school": {
/// "friends": [ {"name": "Millicent Norman"}, {"name": "Vincent Cannon"} ]
/// },
/// "friends": [ {"id": 0}, {"id": 1} ]
/// });
///
2019-03-14 22:30:42 +09:00
/// let json = template(&json_obj).unwrap();
2019-03-05 23:48:27 +09:00
/// let ret = json!([ {"id": 0}, {"name": "Millicent Norman"} ]);
/// assert_eq!(json, ret);
/// ```
2019-03-24 21:18:58 +09:00
pub fn compile<'a>(path: &'a str) -> impl FnMut(&Value) -> result::Result<Value, String> + 'a {
2019-02-26 23:04:04 +09:00
let mut parser = Parser::new(path);
let node = parser.compile();
move |json| {
match &node {
Ok(n) => {
2019-03-11 17:35:15 +09:00
let mut jf = JsonValueFilter::new_from_value(json.into());
2019-02-26 23:04:04 +09:00
jf.visit(n.clone());
Ok(jf.take_value().into())
2019-03-05 23:48:27 +09:00
}
2019-02-26 23:04:04 +09:00
Err(e) => Err(e.clone())
}
}
}
2019-03-05 23:48:27 +09:00
2019-03-24 21:18:58 +09:00
/// # Use multiple JsonPaths for one JsonObject.
2019-03-05 23:48:27 +09:00
///
/// ```rust
2019-03-06 23:50:10 +09:00
/// extern crate jsonpath_lib as jsonpath;
/// #[macro_use] extern crate serde_json;
///
2019-03-05 23:48:27 +09:00
/// let json_obj = json!({
/// "school": {
/// "friends": [{"id": 0}, {"id": 1}]
/// },
/// "friends": [{"id": 0},{"id": 1}]
/// });
///
2019-03-14 22:30:42 +09:00
/// let mut selector = jsonpath::selector(&json_obj);
2019-03-05 23:48:27 +09:00
///
2019-03-11 17:35:15 +09:00
/// let json = selector("$..friends[0]").unwrap();
2019-03-05 23:48:27 +09:00
/// let ret = json!([ {"id": 0}, {"id": 0} ]);
/// assert_eq!(json, ret);
///
2019-03-11 17:35:15 +09:00
/// let json = selector("$..friends[1]").unwrap();
2019-03-05 23:48:27 +09:00
/// let ret = json!([ {"id": 1}, {"id": 1} ]);
/// assert_eq!(json, ret);
/// ```
2019-03-24 21:18:58 +09:00
pub fn selector(json: &Value) -> impl FnMut(&str) -> result::Result<Value, String> {
2019-03-11 17:35:15 +09:00
let wrapper: RefValueWrapper = json.into();
2019-03-03 00:33:27 +09:00
move |path: &str| {
2019-03-11 17:35:15 +09:00
let mut jf = JsonValueFilter::new_from_value(wrapper.clone());
2019-03-03 00:33:27 +09:00
let mut parser = Parser::new(path);
parser.parse(&mut jf)?;
Ok(jf.take_value().into())
2019-03-03 00:33:27 +09:00
}
}
2019-04-01 14:32:20 +09:00
#[deprecated(since = "0.1.4", note = "Please use the selector function instead")]
2019-03-24 21:18:58 +09:00
pub fn reader(json: &Value) -> impl FnMut(&str) -> result::Result<Value, String> {
2019-03-11 17:35:15 +09:00
selector(json)
}
2019-03-24 21:18:58 +09:00
/// # Select a JsonObject
2019-03-05 23:48:27 +09:00
///
/// ```rust
2019-03-06 23:50:10 +09:00
/// extern crate jsonpath_lib as jsonpath;
/// #[macro_use] extern crate serde_json;
///
2019-03-05 23:48:27 +09:00
/// let json_obj = json!({
/// "school": {
/// "friends": [{"id": 0}, {"id": 1}]
/// },
/// "friends": [{"id": 0}, {"id": 1}]
/// });
2019-03-14 22:30:42 +09:00
/// let json = jsonpath::select(&json_obj, "$..friends[0]").unwrap();
2019-03-05 23:48:27 +09:00
/// let ret = json!([ {"id": 0}, {"id": 0} ]);
/// assert_eq!(json, ret);
/// ```
2019-03-24 21:18:58 +09:00
pub fn select(json: &Value, path: &str) -> result::Result<Value, String> {
2019-03-11 17:35:15 +09:00
let mut jf = JsonValueFilter::new_from_value(json.into());
2019-02-26 23:04:04 +09:00
let mut parser = Parser::new(path);
parser.parse(&mut jf)?;
Ok(jf.take_value().into())
2019-03-11 17:35:15 +09:00
}
2019-04-01 14:32:20 +09:00
#[deprecated(since = "0.1.4", note = "Please use the select function instead")]
2019-03-24 21:18:58 +09:00
pub fn read(json: &Value, path: &str) -> result::Result<Value, String> {
2019-03-11 17:35:15 +09:00
select(json, path)
2019-03-03 00:33:27 +09:00
}
2019-03-05 23:48:27 +09:00
2019-04-01 14:32:20 +09:00
#[deprecated(since = "0.1.7", note = "Please use the select_as_str function instead")]
2019-03-24 21:18:58 +09:00
pub fn select_str(json: &str, path: &str) -> result::Result<String, String> {
select_as_str(json, path)
}
/// # Return to json string
///
/// ```rust
/// extern crate jsonpath_lib as jsonpath;
/// #[macro_use] extern crate serde_json;
///
2019-03-24 21:18:58 +09:00
/// let ret = jsonpath::select_as_str(r#"{
2019-03-23 11:51:35 +09:00
/// "school": { "friends": [{"id": 0}, {"id": 1}] },
/// "friends": [{"id": 0}, {"id": 1}]
/// }"#, "$..friends[0]").unwrap();
/// assert_eq!(ret, r#"[{"id":0},{"id":0}]"#);
/// ```
2019-03-24 21:18:58 +09:00
pub fn select_as_str(json: &str, path: &str) -> result::Result<String, String> {
let ref_value: RefValue = serde_json::from_str(json).map_err(|e| format!("{:?}", e))?;
let mut jf = JsonValueFilter::new_from_value(ref_value.into());
let mut parser = Parser::new(path);
parser.parse(&mut jf)?;
serde_json::to_string(&jf.take_value().deref()).map_err(|e| format!("{:?}", e))
}
/// # Return to deserializeable.
/// ```rust
/// extern crate jsonpath_lib as jsonpath;
/// extern crate serde;
/// #[macro_use] extern crate serde_json;
///
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize, PartialEq, Debug)]
2019-03-24 21:18:58 +09:00
/// struct Person {
/// name: String,
/// age: u8,
/// phones: Vec<String>,
/// }
///
/// let ret: Person = jsonpath::select_as(r#"
/// {
/// "person":
/// {
/// "name": "Doe John",
/// "age": 44,
/// "phones": [
/// "+44 1234567",
/// "+44 2345678"
/// ]
/// }
/// }
/// "#, "$.person").unwrap();
///
/// let person = Person {
/// name: "Doe John".to_string(),
/// age: 44,
/// phones: vec!["+44 1234567".to_string(), "+44 2345678".to_string()],
/// };
///
/// assert_eq!(person, ret);
/// ```
pub fn select_as<'a, T: serde::Deserialize<'a>>(json: &str, path: &str) -> result::Result<T, String> {
let ref_value: RefValue = serde_json::from_str(json).map_err(|e| format!("{:?}", e))?;
let mut jf = JsonValueFilter::new_from_value(ref_value.into());
let mut parser = Parser::new(path);
parser.parse(&mut jf)?;
2019-03-24 21:18:58 +09:00
T::deserialize(jf.take_value().deref()).map_err(|e| format!("{:?}", e))
}