Skip to content

Commit 47bd5f6

Browse files
dangradmlb2000
authored andcommitted
Add handy shortcut to match string path (#25)
* Add handy shortcut to match string path This change aims to avoid the boilerplate of applying a JsonPath to a document ```python >>> import jsonpath2 as jsonpath >>> doc = {'hello': 'Hello, world!'} >>> [m.current_value for m in jsonpath.match('$["hello"]', doc)] ``` It resembles the use of `re` module in `re.match(pattern, string)` vs `re.compile(pattern).match(string)` * Add test case for jsonpath2.match shortcut * Use shorter idiomatic python for README examples (#24) * Update README
1 parent ecee29d commit 47bd5f6

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,19 @@ This repository contains an implementation of [JSONPath](http://goessner.net/art
55

66
## API
77

8+
9+
### `match` shortcut function
10+
11+
The `jsonpath2.match` function is a shortcut to match a given JSON data
12+
structure against a JSONPath string
13+
14+
```python
15+
>>> import jsonpath2
16+
>>> doc = {'hello': 'Hello, world!'}
17+
>>> [x.current_value for x in jsonpath2.match('$.hello', doc)]
18+
['Hello, world!']
19+
```
20+
821
### `Path` class
922

1023
The `jsonpath2.path.Path` class represents a JSONPath.

jsonpath2/__init__.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,13 @@
11
#!/usr/bin/python
22
# -*- coding: utf-8 -*-
33
"""The jsonpath2 module."""
4+
5+
from typing import Generator
6+
from .path import Path
7+
from .node import MatchData
8+
9+
10+
def match(path_str: str, root_value: object) -> Generator[MatchData, None, None]:
11+
"""Match root value of the path."""
12+
path = Path.parse_str(path_str)
13+
return path.match(root_value)

jsonpath2/test/shortcuts_test.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
3+
"""Test package level shortcuts."""
4+
5+
from unittest import TestCase
6+
import jsonpath2
7+
8+
9+
class TestShortcuts(TestCase):
10+
"""Test package level shortcuts."""
11+
12+
def test_match(self):
13+
"""Test match shortcut works."""
14+
data = {'hello': 'Hello, World!'}
15+
self.assertEqual(
16+
[x.current_value for x in jsonpath2.match('$.hello', data)],
17+
['Hello, World!']
18+
)

0 commit comments

Comments
 (0)