|
| 1 | +# Python JSONPath |
| 2 | + |
| 3 | +JSONPath is a mini language for selecting objects from data formatted in JavaScript Object Notation, or equivalent Python objects, like dictionaries and lists. |
| 4 | + |
| 5 | +## Install |
| 6 | + |
| 7 | +Install Python JSONPath using [pip](https://pip.pypa.io/en/stable/getting-started/): |
| 8 | + |
| 9 | +```console |
| 10 | +pip install python-jsonpath |
| 11 | +``` |
| 12 | + |
| 13 | +Or [Pipenv](https://pipenv.pypa.io/en/latest/): |
| 14 | + |
| 15 | +```console |
| 16 | +pipenv install python-jsonpath |
| 17 | +``` |
| 18 | + |
| 19 | +## Example |
| 20 | + |
| 21 | +```python |
| 22 | +import jsonpath |
| 23 | + |
| 24 | +example_data = { |
| 25 | + "categories": [ |
| 26 | + { |
| 27 | + "name": "footwear", |
| 28 | + "products": [ |
| 29 | + { |
| 30 | + "title": "Trainers", |
| 31 | + "description": "Fashionable trainers.", |
| 32 | + "price": 89.99, |
| 33 | + }, |
| 34 | + { |
| 35 | + "title": "Barefoot Trainers", |
| 36 | + "description": "Running trainers.", |
| 37 | + "price": 130.00, |
| 38 | + }, |
| 39 | + ], |
| 40 | + }, |
| 41 | + { |
| 42 | + "name": "headwear", |
| 43 | + "products": [ |
| 44 | + { |
| 45 | + "title": "Cap", |
| 46 | + "description": "Baseball cap", |
| 47 | + "price": 15.00, |
| 48 | + }, |
| 49 | + { |
| 50 | + "title": "Beanie", |
| 51 | + "description": "Winter running hat.", |
| 52 | + "price": 9.00, |
| 53 | + }, |
| 54 | + ], |
| 55 | + }, |
| 56 | + ], |
| 57 | + "price_cap": 10, |
| 58 | +} |
| 59 | + |
| 60 | +products = jsonpath.findall("$..products.*", example_data) |
| 61 | +print(products) |
| 62 | +``` |
| 63 | + |
| 64 | +Which results in a list of all products from all categories: |
| 65 | + |
| 66 | +```json |
| 67 | +[ |
| 68 | + { |
| 69 | + "title": "Trainers", |
| 70 | + "description": "Fashionable trainers.", |
| 71 | + "price": 89.99 |
| 72 | + }, |
| 73 | + { |
| 74 | + "title": "Barefoot Trainers", |
| 75 | + "description": "Running trainers.", |
| 76 | + "price": 130.0 |
| 77 | + }, |
| 78 | + { |
| 79 | + "title": "Cap", |
| 80 | + "description": "Baseball cap", |
| 81 | + "price": 15.0 |
| 82 | + }, |
| 83 | + { |
| 84 | + "title": "Beanie", |
| 85 | + "description": "Winter running hat.", |
| 86 | + "price": 9.0 |
| 87 | + } |
| 88 | +] |
| 89 | +``` |
| 90 | + |
| 91 | +Or, reading data from a JSON formatted file: |
| 92 | + |
| 93 | +```python |
| 94 | +import jsonpath |
| 95 | + |
| 96 | +with open("some.json") as fd: |
| 97 | + products = jsonpath.findall("$..products.*", fd) |
| 98 | + |
| 99 | +print(products) |
| 100 | +``` |
| 101 | + |
| 102 | +## Next Steps |
| 103 | + |
| 104 | +Have a read through the [Quick Start](quickstart.md) and [High Level API Reference](api.md). |
| 105 | + |
| 106 | +If you're interested in customizing JSONPath, take a look at [Advanced Usage](advanced.md) and the [Low Level API Reference](custom_api.md). |
0 commit comments