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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! JsonPath implementation written in Rust.
//!
//! # Example
//! ```
//! extern crate jsonpath_lib as jsonpath;
//! #[macro_use] extern crate serde_json;
//! let json_obj = json!({
//!     "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
//! });
//!
//! let mut selector = jsonpath::selector(&json_obj);
//!
//! assert_eq!(selector("$.store.book[*].author").unwrap(),
//!             vec![
//!                 "Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"
//!             ]);
//!
//! assert_eq!(selector("$..author").unwrap(),
//!             vec![
//!                 "Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"
//!             ]);
//!
//! assert_eq!(selector("$.store.*").unwrap(),
//!             vec![
//!                 &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 }
//!                 ]),
//!                 &json!({ "color": "red", "price": 19.95 })
//!             ]);
//!
//! assert_eq!(selector("$.store..price").unwrap(),
//!             vec![
//!                 8.95, 12.99, 8.99, 22.99, 19.95
//!             ]);
//!
//! assert_eq!(selector("$..book[2]").unwrap(),
//!             vec![
//!                 &json!({
//!                     "category" : "fiction",
//!                     "author" : "Herman Melville",
//!                     "title" : "Moby Dick",
//!                     "isbn" : "0-553-21311-3",
//!                     "price" : 8.99
//!                 })
//!             ]);
//!
//! assert_eq!(selector("$..book[-2]").unwrap(),
//!             vec![
//!                 &json!({
//!                     "category" : "fiction",
//!                     "author" : "Herman Melville",
//!                     "title" : "Moby Dick",
//!                     "isbn" : "0-553-21311-3",
//!                     "price" : 8.99
//!                 })
//!             ]);
//!
//! assert_eq!(selector("$..book[0,1]").unwrap(),
//!             vec![
//!                 &json!({"category" : "reference","author" : "Nigel Rees","title" : "Sayings of the Century","price" : 8.95}),
//!                 &json!({"category" : "fiction","author" : "Evelyn Waugh","title" : "Sword of Honour","price" : 12.99})
//!             ]);
//!
//! assert_eq!(selector("$..book[:2]").unwrap(),
//!             vec![
//!                 &json!({"category" : "reference","author" : "Nigel Rees","title" : "Sayings of the Century","price" : 8.95}),
//!                 &json!({"category" : "fiction","author" : "Evelyn Waugh","title" : "Sword of Honour","price" : 12.99})
//!             ]);
//!
//! assert_eq!(selector("$..book[:2]").unwrap(),
//!             vec![
//!                 &json!({"category" : "reference","author" : "Nigel Rees","title" : "Sayings of the Century","price" : 8.95}),
//!                 &json!({"category" : "fiction","author" : "Evelyn Waugh","title" : "Sword of Honour","price" : 12.99})
//!             ]);
//!
//! assert_eq!(selector("$..book[?(@.isbn)]").unwrap(),
//!             vec![
//!                 &json!({"category" : "fiction","author" : "Herman Melville","title" : "Moby Dick","isbn" : "0-553-21311-3","price" : 8.99}),
//!                 &json!({"category" : "fiction","author" : "J. R. R. Tolkien","title" : "The Lord of the Rings","isbn" : "0-395-19395-8","price" : 22.99})
//!             ]);
//!
//! assert_eq!(selector("$.store.book[?(@.price < 10)]").unwrap(),
//!             vec![
//!                 &json!({"category" : "reference","author" : "Nigel Rees","title" : "Sayings of the Century","price" : 8.95}),
//!                 &json!({"category" : "fiction","author" : "Herman Melville","title" : "Moby Dick","isbn" : "0-553-21311-3","price" : 8.99})
//!             ]);
//! ```
extern crate array_tool;
extern crate core;
extern crate env_logger;
#[macro_use]
extern crate log;
extern crate serde;
extern crate serde_json;

use serde_json::Value;

pub use parser::parser::{Node, Parser};
pub use select::JsonPathError;
pub use select::{Selector, SelectorMut};

#[doc(hidden)]
mod parser;
#[doc(hidden)]
mod select;

/// It is a high-order function. it compile a jsonpath and then returns a closure that has JSON as argument. if you need to reuse a jsonpath, it is good for performance.
///
/// ```rust
/// extern crate jsonpath_lib as jsonpath;
/// #[macro_use] extern crate serde_json;
///
/// let mut first_firend = jsonpath::compile("$..friends[0]");
///
/// let json_obj = json!({
///     "school": {
///         "friends": [
///             {"name": "친구1", "age": 20},
///             {"name": "친구2", "age": 20}
///         ]
///     },
///     "friends": [
///         {"name": "친구3", "age": 30},
///         {"name": "친구4"}
/// ]});
///
/// let json = first_firend(&json_obj).unwrap();
///
/// assert_eq!(json, vec![
///     &json!({"name": "친구3", "age": 30}),
///     &json!({"name": "친구1", "age": 20})
/// ]);
/// ```
pub fn compile(path: &str) -> impl FnMut(&Value) -> Result<Vec<&Value>, JsonPathError> {
    let node = Parser::compile(path);
    move |json| match &node {
        Ok(node) => {
            let mut selector = Selector::new();
            selector.compiled_path(node).value(json).select()
        }
        Err(e) => Err(JsonPathError::Path(e.to_string())),
    }
}

/// It is a high-order function. it returns a closure that has a jsonpath string as argument. you can use diffenent jsonpath for one JSON object.
///
/// ```rust
/// extern crate jsonpath_lib as jsonpath;
/// #[macro_use] extern crate serde_json;
///
/// let json_obj = json!({
///     "school": {
///         "friends": [
///             {"name": "친구1", "age": 20},
///             {"name": "친구2", "age": 20}
///         ]
///     },
///     "friends": [
///         {"name": "친구3", "age": 30},
///         {"name": "친구4"}
/// ]});
///
/// let mut selector = jsonpath::selector(&json_obj);
///
/// let json = selector("$..friends[0]").unwrap();
///
/// assert_eq!(json, vec![
///     &json!({"name": "친구3", "age": 30}),
///     &json!({"name": "친구1", "age": 20})
/// ]);
///
/// let json = selector("$..friends[1]").unwrap();
///
/// assert_eq!(json, vec![
///     &json!({"name": "친구4"}),
///     &json!({"name": "친구2", "age": 20})
/// ]);
/// ```
pub fn selector<'a>(json: &'a Value) -> impl FnMut(&'a str) -> Result<Vec<&Value>, JsonPathError> {
    let mut selector = Selector::new();
    let _ = selector.value(json);
    move |path: &str| selector.str_path(path)?.reset_value().select()
}

/// It is the same to `selector` function. but it deserialize the result as given type `T`.
///
/// ```rust
/// extern crate jsonpath_lib as jsonpath;
/// extern crate serde;
/// #[macro_use] extern crate serde_json;
///
/// use serde::{Deserialize, Serialize};
///
/// let json_obj = json!({
///     "school": {
///         "friends": [
///             {"name": "친구1", "age": 20},
///             {"name": "친구2", "age": 20}
///         ]
///     },
///     "friends": [
///         {"name": "친구3", "age": 30},
///         {"name": "친구4"}
/// ]});
///
/// #[derive(Deserialize, PartialEq, Debug)]
/// struct Friend {
///     name: String,
///     age: Option<u8>,
/// }
///
/// let mut selector = jsonpath::selector_as::<Friend>(&json_obj);
///
/// let json = selector("$..friends[0]").unwrap();
///
/// let ret = vec!(
///     Friend { name: "친구3".to_string(), age: Some(30) },
///     Friend { name: "친구1".to_string(), age: Some(20) }
/// );
/// assert_eq!(json, ret);
///
/// let json = selector("$..friends[1]").unwrap();
///
/// let ret = vec!(
///     Friend { name: "친구4".to_string(), age: None },
///     Friend { name: "친구2".to_string(), age: Some(20) }
/// );
///
/// assert_eq!(json, ret);
/// ```
pub fn selector_as<T: serde::de::DeserializeOwned>(
    json: &Value,
) -> impl FnMut(&str) -> Result<Vec<T>, JsonPathError> + '_ {
    let mut selector = Selector::new();
    let _ = selector.value(json);
    move |path: &str| selector.str_path(path)?.reset_value().select_as()
}

/// It is a simple select function. but it compile the jsonpath argument every time.
///
/// ```rust
/// extern crate jsonpath_lib as jsonpath;
/// #[macro_use] extern crate serde_json;
///
/// let json_obj = json!({
///     "school": {
///         "friends": [
///             {"name": "친구1", "age": 20},
///             {"name": "친구2", "age": 20}
///         ]
///     },
///     "friends": [
///         {"name": "친구3", "age": 30},
///         {"name": "친구4"}
/// ]});
///
/// let json = jsonpath::select(&json_obj, "$..friends[0]").unwrap();
///
/// assert_eq!(json, vec![
///     &json!({"name": "친구3", "age": 30}),
///     &json!({"name": "친구1", "age": 20})
/// ]);
/// ```
pub fn select<'a>(json: &'a Value, path: &'a str) -> Result<Vec<&'a Value>, JsonPathError> {
    Selector::new().str_path(path)?.value(json).select()
}

/// It is the same to `select` function but it return the result as string.
///
/// ```rust
/// extern crate jsonpath_lib as jsonpath;
/// #[macro_use] extern crate serde_json;
///
/// let ret = jsonpath::select_as_str(r#"
/// {
///     "school": {
///         "friends": [
///                 {"name": "친구1", "age": 20},
///                 {"name": "친구2", "age": 20}
///             ]
///     },
///     "friends": [
///         {"name": "친구3", "age": 30},
///         {"name": "친구4"}
///     ]
/// }
/// "#, "$..friends[0]").unwrap();
///
/// assert_eq!(ret, r#"[{"name":"친구3","age":30},{"name":"친구1","age":20}]"#);
/// ```
pub fn select_as_str(json_str: &str, path: &str) -> Result<String, JsonPathError> {
    let json = serde_json::from_str(json_str).map_err(|e| JsonPathError::Serde(e.to_string()))?;
    let ret = Selector::new().str_path(path)?.value(&json).select()?;
    serde_json::to_string(&ret).map_err(|e| JsonPathError::Serde(e.to_string()))
}

/// It is the same to `select` function but it deserialize the the result as given type `T`.
///
/// ```rust
/// extern crate jsonpath_lib as jsonpath;
/// extern crate serde;
/// #[macro_use] extern crate serde_json;
///
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize, PartialEq, Debug)]
/// struct Person {
///     name: String,
///     age: u8,
///     phones: Vec<String>,
/// }
///
/// let ret: Vec<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!(ret[0], person);
/// ```
pub fn select_as<T: serde::de::DeserializeOwned>(
    json_str: &str,
    path: &str,
) -> Result<Vec<T>, JsonPathError> {
    let json = serde_json::from_str(json_str).map_err(|e| JsonPathError::Serde(e.to_string()))?;
    Selector::new().str_path(path)?.value(&json).select_as()
}

/// Delete(= replace with null) the JSON property using the jsonpath.
///
/// ```rust
/// extern crate jsonpath_lib as jsonpath;
/// #[macro_use] extern crate serde_json;
///
/// let json_obj = json!({
///     "school": {
///         "friends": [
///             {"name": "친구1", "age": 20},
///             {"name": "친구2", "age": 20}
///         ]
///     },
///     "friends": [
///         {"name": "친구3", "age": 30},
///         {"name": "친구4"}
/// ]});
///
/// let ret = jsonpath::delete(json_obj, "$..[?(20 == @.age)]").unwrap();
///
/// assert_eq!(ret, json!({
///     "school": {
///         "friends": [
///             null,
///             null
///         ]
///     },
///     "friends": [
///         {"name": "친구3", "age": 30},
///         {"name": "친구4"}
/// ]}));
/// ```
pub fn delete(value: Value, path: &str) -> Result<Value, JsonPathError> {
    let mut selector = SelectorMut::new();
    let ret = selector
        .str_path(path)?
        .value(value)
        .delete()?
        .take()
        .unwrap_or(Value::Null);
    Ok(ret)
}

/// Select JSON properties using a jsonpath and transform the result and then replace it. via closure that implements `FnMut` you can transform the selected results.
///
/// ```rust
/// extern crate jsonpath_lib as jsonpath;
/// #[macro_use] extern crate serde_json;
///
/// use serde_json::Value;
///
/// let json_obj = json!({
///     "school": {
///         "friends": [
///             {"name": "친구1", "age": 20},
///             {"name": "친구2", "age": 20}
///         ]
///     },
///     "friends": [
///         {"name": "친구3", "age": 30},
///         {"name": "친구4"}
/// ]});
///
/// let ret = jsonpath::replace_with(json_obj, "$..[?(@.age == 20)].age", &mut |v| {
///     let age = if let Value::Number(n) = v {
///         n.as_u64().unwrap() * 2
///     } else {
///         0
///     };
///
///     json!(age)
/// }).unwrap();
///
/// assert_eq!(ret, json!({
///     "school": {
///         "friends": [
///             {"name": "친구1", "age": 40},
///             {"name": "친구2", "age": 40}
///         ]
///     },
///     "friends": [
///         {"name": "친구3", "age": 30},
///         {"name": "친구4"}
/// ]}));
/// ```
pub fn replace_with<F>(value: Value, path: &str, fun: &mut F) -> Result<Value, JsonPathError>
where
    F: FnMut(&Value) -> Value,
{
    let mut selector = SelectorMut::new();
    let ret = selector
        .str_path(path)?
        .value(value)
        .replace_with(fun)?
        .take()
        .unwrap_or(Value::Null);
    Ok(ret)
}