Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions jsonpath_rw/jsonpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,14 @@ def __repr__(self):
def __eq__(self, other):
return isinstance(other, This)

class SortedThis(This):

def find(self, datum):
"""Return sorted value of This if list or dict."""
if isinstance(datum.value, dict) or isinstance(datum.value, list):
return [DatumInContext.wrap(value) for value in sorted(datum.value)]
return datum

class Child(JSONPath):
"""
JSONPath that first matches the left, then the right.
Expand Down
2 changes: 2 additions & 0 deletions jsonpath_rw/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ def p_jsonpath_named_operator(self, p):
"jsonpath : NAMED_OPERATOR"
if p[1] == 'this':
p[0] = This()
elif p[1] == 'sorted':
p[0] = SortedThis()
elif p[1] == 'parent':
p[0] = Parent()
else:
Expand Down
5 changes: 4 additions & 1 deletion tests/test_jsonpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,10 @@ def test_fields_value(self):
self.check_cases([ ('foo', {'foo': 'baz'}, ['baz']),
('foo,baz', {'foo': 1, 'baz': 2}, [1, 2]),
('@foo', {'@foo': 1}, [1]),
('*', {'foo': 1, 'baz': 2}, set([1, 2])) ])
('*', {'foo': 1, 'baz': 2}, set([1, 2])),
('objects.`sorted`', {'objects': ['alpha', 'gamma', 'beta']}, ['alpha', 'beta', 'gamma']),
('objects.`sorted`', {'objects': {'cow': 'moo', 'horse': 'neigh', 'cat': 'meow'}}, ['cat', 'cow', 'horse']),
])

jsonpath.auto_id_field = 'id'
self.check_cases([ ('*', {'foo': 1, 'baz': 2}, set([1, 2, '`this`'])) ])
Expand Down