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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! # Json path
//! The library provides the basic functionality
//! to find the slice of data according to the query.
//! The idea comes from xpath for xml structures.
//! The details can be found over [`there`]
//! Therefore JSONPath is a query language for JSON,
//! similar to XPath for XML. The jsonpath query is a set of assertions to specify the JSON fields that need to be verified.
//!
//! # Simple example
//! Let's suppose we have a following json:
//! ```json
//!  {
//!   "shop": {
//!    "orders": [
//!       {"id": 1, "active": true},
//!       {"id": 2 },
//!       {"id": 3 },
//!       {"id": 4, "active": true}
//!     ]
//!   }
//! }
//! ```
//! And we pursue to find all orders id having the field 'active'
//! we can construct the jsonpath instance like that
//! ```$.shop.orders[?(@.active)].id``` and get the result ``` [1,4] ```
//!
//! # Another examples
//! ```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
//!     }
//!   }
//! }
//! ```
//! and examples
//! - ``` $.store.book[*].author ``` : the authors of all books in the store
//! - ``` $..book[?(@.isbn)]``` : filter all books with isbn number
//! - ``` $..book[?(@.price<10)]``` : filter all books cheapier than 10
//! - ``` $..*``` : all Elements in XML document. All members of JSON structure
//! - ``` $..book[0,1]``` : The first two books
//! - ``` $..book[:2]``` : The first two books
//!
//! # Operators
//!
//! - `$` : Pointer to the root of the json. It is gently advising to start every jsonpath from the root. Also, inside the filters to point out that the path is starting from the root.
//! - `@`Pointer to the current element inside the filter operations.It is used inside the filter operations to iterate the collection.
//! - `*` or `[*]`Wildcard. It brings to the list all objects and elements regardless their names.It is analogue a flatmap operation.
//! - `<..>`| Descent operation. It brings to the list all objects, children of that objects and etc It is analogue a flatmap operation.
//! - `.<name>` or `.['<name>']`the key pointing to the field of the objectIt is used to obtain the specific field.
//! - `['<name>' (, '<name>')]`the list of keysthe same usage as for a single key but for list
//! - `[<number>]`the filter getting the element by its index.
//! - `[<number> (, <number>)]`the list if elements of array according to their indexes representing these numbers. |
//! - `[<start>:<end>:<step>]`slice operator to get a list of element operating with their indexes. By default step = 1, start = 0, end = array len. The elements can be omitted ```[:]```
//! - `[?(<expression>)]`the logical expression to filter elements in the list.It is used with arrays preliminary.
//!
//! # Examples
//!```
//! use serde_json::{json,Value};
//! use self::jsonpath_rust::JsonPathFinder;
//! fn test(){
//!     let finder = JsonPathFinder::from_str(r#"{"first":{"second":[{"active":1},{"passive":1}]}}"#, "$.first.second[?(@.active)]").unwrap();
//!     let slice_of_data:Vec<&Value> = finder.find_slice();
//!     assert_eq!(slice_of_data, vec![&json!({"active":1})]);
//! }
//! ```
//! or even simpler:
//!
//! ```
//! use serde_json::{json,Value};
//! use self::jsonpath_rust::JsonPathFinder;
//!
//! fn test(json: &str, path: &str, expected: Vec<&Value>) {
//!    match JsonPathFinder::from_str(json, path) {
//!        Ok(finder) => assert_eq!(finder.find_slice(), expected),
//!        Err(e) => panic!("error while parsing json or jsonpath: {}", e)
//!    }
//! }
//! ```
//!
//! [`there`]: https://goessner.net/articles/JsonPath/


use serde_json::{Value};
use crate::parser::parser::parse_json_path;
use crate::path::{json_path_instance, PathInstance};
use crate::parser::model::JsonPath;

mod parser;
mod path;


#[macro_use]
extern crate pest_derive;
extern crate pest;

/// the trait allows to mix the method path to the value of [Value]
/// and thus the using can be shortened to the following one:
/// # Examples:
/// ```
/// use serde_json::{json,Value};
/// use jsonpath_rust::JsonPathQuery;
///fn test(){
///         let json: Value = serde_json::from_str("{}").expect("to get json");
///         let v = json.path("$..book[?(@.author size 10)].title").expect("the path is correct");
///         assert_eq!(v, json!([]));
/// }
/// ```
/// #Note:
/// the result is going to be cloned and therefore it can be significant for the huge queries
pub trait JsonPathQuery {
    fn path(self, query: &str) -> Result<Value, String>;
}

impl JsonPathQuery for Value {
    fn path(self, query: &str) -> Result<Value, String> {
        let p = parse_json_path(query).map_err(|e| e.to_string())?;
        Ok(JsonPathFinder::new(self, p).find())
    }
}


/// The base structure conjuncting the json instance and jsonpath instance
pub struct JsonPathFinder {
    json: Value,
    path: JsonPath,
}

impl JsonPathFinder {
    /// creates a new instance of [JsonPathFinder]
    pub fn new(json: Value, path: JsonPath) -> Self {
        JsonPathFinder { json, path }
    }

    /// updates a path with a new one
    pub fn set_path(&mut self, path: JsonPath) {
        self.path = path
    }
    /// updates a json with a new one
    pub fn set_json(&mut self, json: Value) {
        self.json = json
    }
    /// updates a json from string and therefore can be some parsing errors
    pub fn set_json_str(&mut self, json: &str) -> Result<(), String> {
        self.json = serde_json::from_str(json).map_err(|e| e.to_string())?;
        Ok(())
    }
    /// updates a path from string and therefore can be some parsing errors
    pub fn set_path_str(&mut self, path: &str) -> Result<(), String> {
        self.path = parse_json_path(path).map_err(|e| e.to_string())?;
        Ok(())
    }

    /// create a new instance from string and therefore can be some parsing errors
    pub fn from_str(json: &str, path: &str) -> Result<Self, String> {
        let json = serde_json::from_str(json).map_err(|e| e.to_string())?;
        let path = parse_json_path(path).map_err(|e| e.to_string())?;
        Ok(JsonPathFinder::new(json, path))
    }

    /// creates an instance to find a json slice from the json
    pub fn instance(&self) -> PathInstance {
        json_path_instance(&self.path, &self.json)
    }
    /// finds a slice of data in the set json.
    /// The result is a vector of references to the incoming structure.
    pub fn find_slice(&self) -> Vec<&Value> {
        self.instance().find(&self.json)
    }

    /// finds a slice of data and wrap it with Value::Array by cloning the data.
    pub fn find(&self) -> Value {
        Value::Array(self.find_slice().into_iter().map(|x| x.clone()).collect())
    }
}

#[cfg(test)]
mod tests {
    use serde_json::{json, Value};
    use crate::JsonPathFinder;
    use crate::JsonPathQuery;

    fn test(json: &str, path: &str, expected: Vec<&Value>) {
        match JsonPathFinder::from_str(json, path) {
            Ok(finder) => assert_eq!(finder.find_slice(), expected),
            Err(e) => panic!("error while parsing json or jsonpath: {}", e)
        }
    }

    fn template_json<'a>() -> &'a str {
        r#" {"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
         }
     },
     "array":[0,1,2,3,4,5,6,7,8,9],
     "orders":[{"ref":[1,2,3],"id":1},{"ref":[4,5,6],"id":2},{"ref":[7,8,9],"id":3}],
     "expensive": 10 }"#
    }

    #[test]
    fn simple_test() {
        test("[1,2,3]", "$[1]", vec![&json!(2)]);
    }

    #[test]
    fn root_test() {
        test(template_json(), "$", vec![&serde_json::from_str(template_json()).unwrap()]);
    }

    #[test]
    fn descent_test() {
        test(template_json(), "$..category",
             vec![
                 &json!("reference"),
                 &json!("fiction"),
                 &json!("fiction"),
                 &json!("fiction"),
             ]);
        test(template_json(),
             "$.store..price",
             vec![
                 &json!(19.95),
                 &json!(8.95),
                 &json!(12.99),
                 &json!(8.99),
                 &json!(22.99),
             ],
        );
        test(template_json(),
             "$..author",
             vec![
                 &json!("Nigel Rees"),
                 &json!("Evelyn Waugh"),
                 &json!("Herman Melville"),
                 &json!("J. R. R. Tolkien"),
             ],
        );
    }

    #[test]
    fn wildcard_test() {
        test(template_json(), "$..book.[*].category",
             vec![
                 &json!("reference"),
                 &json!("fiction"),
                 &json!("fiction"),
                 &json!("fiction"),
             ]);
        test(template_json(),
             "$.store.book[*].author",
             vec![
                 &json!("Nigel Rees"),
                 &json!("Evelyn Waugh"),
                 &json!("Herman Melville"),
                 &json!("J. R. R. Tolkien"),
             ],
        );
    }

    #[test]
    fn field_test() {
        test(r#"{"field":{"field":[{"active":1},{"passive":1}]}}"#,
             "$.field.field[?(@.active)]",
             vec![&json!({"active":1})]);
    }

    #[test]
    fn index_index_test() {
        test(template_json(), "$..book[2].isbn",
             vec![
                 &json!("0-553-21311-3"),
             ]);
    }

    #[test]
    fn index_unit_index_test() {
        test(template_json(), "$..book[2,4].isbn",
             vec![
                 &json!("0-553-21311-3"),
             ]);
        test(template_json(), "$..book[2,3].isbn",
             vec![
                 &json!("0-553-21311-3"),
                 &json!("0-395-19395-8"),
             ]);
    }

    #[test]
    fn index_unit_keys_test() {
        test(template_json(), "$..book[2,3]['title','price']",
             vec![
                 &json!("Moby Dick"),
                 &json!(8.99),
                 &json!("The Lord of the Rings"),
                 &json!(22.99),
             ]);
    }

    #[test]
    fn index_slice_test() {
        test(template_json(),
             "$.array[:]",
             vec![
                 &json!(0),
                 &json!(1),
                 &json!(2),
                 &json!(3),
                 &json!(4),
                 &json!(5),
                 &json!(6),
                 &json!(7),
                 &json!(8),
                 &json!(9),
             ]);
        test(template_json(),
             "$.array[1:4:2]",
             vec![
                 &json!(1),
                 &json!(3),
             ]);
        test(template_json(),
             "$.array[::3]",
             vec![
                 &json!(0),
                 &json!(3),
                 &json!(6),
                 &json!(9),
             ]);
        test(template_json(),
             "$.array[-1:]",
             vec![
                 &json!(9),
             ]);
        test(template_json(),
             "$.array[-2:-1]",
             vec![
                 &json!(8),
             ]);
    }

    #[test]
    fn index_filter_test() {
        test(template_json(),
             "$..book[?(@.isbn)].title",
             vec![
                 &json!("Moby Dick"),
                 &json!("The Lord of the Rings"),
             ]);
        test(template_json(),
             "$..book[?(@.price != 8.95)].title",
             vec![
                 &json!("Sword of Honour"),
                 &json!("Moby Dick"),
                 &json!("The Lord of the Rings"),
             ]);
        test(template_json(),
             "$..book[?(@.price == 8.95)].title",
             vec![
                 &json!("Sayings of the Century"),
             ]);
        test(template_json(),
             "$..book[?(@.author ~= '.*Rees')].price",
             vec![
                 &json!(8.95),
             ]);
        test(template_json(),
             "$..book[?(@.price >= 8.99)].price",
             vec![
                 &json!(12.99),
                 &json!(8.99),
                 &json!(22.99),
             ]);
        test(template_json(),
             "$..book[?(@.price > 8.99)].price",
             vec![
                 &json!(12.99),
                 &json!(22.99),
             ]);
        test(template_json(),
             "$..book[?(@.price < 8.99)].price",
             vec![
                 &json!(8.95),
             ]);
        test(template_json(),
             "$..book[?(@.price <= 8.99)].price",
             vec![
                 &json!(8.95),
                 &json!(8.99),
             ]);
        test(template_json(),
             "$..book[?(@.price <= $.expensive)].price",
             vec![
                 &json!(8.95),
                 &json!(8.99),
             ]);
        test(template_json(),
             "$..book[?(@.price >= $.expensive)].price",
             vec![
                 &json!(12.99),
                 &json!(22.99),
             ]);
        test(template_json(),
             "$..book[?(@.title in ['Moby Dick','Shmoby Dick','Big Dick','Dicks'])].price",
             vec![
                 &json!(8.99),
             ]);
        test(template_json(),
             "$..book[?(@.title nin ['Moby Dick','Shmoby Dick','Big Dick','Dicks'])].title",
             vec![
                 &json!("Sayings of the Century"),
                 &json!("Sword of Honour"),
                 &json!("The Lord of the Rings"),
             ]);
        test(template_json(),
             "$..book[?(@.author size 10)].title",
             vec![
                 &json!("Sayings of the Century"),
             ]);
    }

    #[test]
    fn index_filter_sets_test() {
        test(template_json(),
             "$.orders[?(@.ref subsetOf [1,2,3,4])].id",
             vec![
                 &json!(1),
             ]);
        test(template_json(),
             "$.orders[?(@.ref anyOf [1,4])].id",
             vec![
                 &json!(1),
                 &json!(2),
             ]);
        test(template_json(),
             "$.orders[?(@.ref noneOf [3,6])].id",
             vec![
                 &json!(3),
             ]);
    }

    #[test]
    fn query_test() {
        let json: Value = serde_json::from_str(template_json()).expect("to get json");
        let v = json.path("$..book[?(@.author size 10)].title")
            .expect("the path is correct");

        assert_eq!(v, json!(["Sayings of the Century"]))
    }
}