|
| 1 | +import pytest |
| 2 | + |
| 3 | +from jsonpath_ng.ext.filter import Filter, Expression |
| 4 | +from jsonpath_ng.ext import parse |
| 5 | +from jsonpath_ng.jsonpath import * |
| 6 | + |
| 7 | + |
| 8 | +@pytest.mark.parametrize('string, parsed', [ |
| 9 | + # The authors of all books in the store |
| 10 | + ("$.store.book[*].author", |
| 11 | + Child(Child(Child(Child(Root(), Fields('store')), Fields('book')), |
| 12 | + Slice()), Fields('author'))), |
| 13 | +
|
| 14 | + # All authors |
| 15 | + ("$..author", Descendants(Root(), Fields('author'))), |
| 16 | +
|
| 17 | + # All things in the store |
| 18 | + ("$.store.*", Child(Child(Root(), Fields('store')), Fields('*'))), |
| 19 | +
|
| 20 | + # The price of everything in the store |
| 21 | + ("$.store..price", |
| 22 | + Descendants(Child(Root(), Fields('store')), Fields('price'))), |
| 23 | +
|
| 24 | + # The third book |
| 25 | + ("$..book[2]", |
| 26 | + Child(Descendants(Root(), Fields('book')),Index(2))), |
| 27 | +
|
| 28 | + # The last book in order |
| 29 | + # ("$..book[(@.length-1)]", # Not implemented |
| 30 | + # Child(Descendants(Root(), Fields('book')), Slice(start=-1))), |
| 31 | + ("$..book[-1:]", |
| 32 | + Child(Descendants(Root(), Fields('book')), Slice(start=-1))), |
| 33 | +
|
| 34 | + # The first two books |
| 35 | + # ("$..book[0,1]", # Not implemented |
| 36 | + # Child(Descendants(Root(), Fields('book')), Slice(end=2))), |
| 37 | + ("$..book[:2]", |
| 38 | + Child(Descendants(Root(), Fields('book')), Slice(end=2))), |
| 39 | +
|
| 40 | + # Filter all books with ISBN number |
| 41 | + ("$..book[?(@.isbn)]", |
| 42 | + Child(Descendants(Root(), Fields('book')), |
| 43 | + Filter([Expression(Child(This(), Fields('isbn')), None, None)]))), |
| 44 | +
|
| 45 | + # Filter all books cheaper than 10 |
| 46 | + ("$..book[?(@.price<10)]", |
| 47 | + Child(Descendants(Root(), Fields('book')), |
| 48 | + Filter([Expression(Child(This(), Fields('price')), '<', 10)]))), |
| 49 | +
|
| 50 | + # All members of JSON structure |
| 51 | + ("$..*", Descendants(Root(), Fields('*'))), |
| 52 | +]) |
| 53 | +def test_goessner_examples(string, parsed): |
| 54 | + """ |
| 55 | + Test Stefan Goessner's `examples`_ |
| 56 | +
|
| 57 | + .. _examples: https://goessner.net/articles/JsonPath/index.html#e3 |
| 58 | + """ |
| 59 | + assert parse(string, debug=True) == parsed |
| 60 | + |
| 61 | + |
| 62 | +@pytest.mark.parametrize('string, parsed', [ |
| 63 | + # Navigate objects |
| 64 | + ("$.store.book[0].title", |
| 65 | + Child(Child(Child(Child(Root(), Fields('store')), Fields('book')), |
| 66 | + Index(0)), Fields('title'))), |
| 67 | +
|
| 68 | + # Navigate dictionaries |
| 69 | + ("$['store']['book'][0]['title']", |
| 70 | + Child(Child(Child(Child(Root(), Fields('store')), Fields('book')), |
| 71 | + Index(0)), Fields('title'))), |
| 72 | +]) |
| 73 | +def test_obj_v_dict(string, parsed): |
| 74 | + assert parse(string, debug=True) == parsed |
0 commit comments