Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 14c60d3

Browse files
committed
Enable iterators to be usable in places where lists are expected
1 parent 2abaf91 commit 14c60d3

3 files changed

Lines changed: 15 additions & 4 deletions

File tree

jsonpath_rw/jsonpath.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import logging
2+
import six
23
from itertools import *
34

45
logger = logging.getLogger(__name__)
@@ -265,11 +266,19 @@ def __init__(self, start=None, end=None, step=None):
265266
self.step = step
266267

267268
def find(self, data):
268-
# Here's the hack. If not a list, try again as though it were.
269-
if not isinstance(data, list):
269+
# Here's the hack. If it is a dictionary or some kind of constant,
270+
# put it in a single-element list
271+
if (isinstance(data, dict) or isinstance(data, six.integer_types)
272+
or isinstance(data, six.string_types)):
273+
270274
return self.find([data])
271275

272-
return data[self.start:self.end:self.step]
276+
# Some iterators do not support slicing but we can still
277+
# at least work for '*'
278+
if self.start == None and self.end == None and self.step == None:
279+
return data
280+
else:
281+
return data[self.start:self.end:self.step]
273282

274283
def __str__(self):
275284
if self.start == None and self.end == None and self.step == None:

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,5 @@
1717
long_description=open('README.txt').read(),
1818
packages = ['jsonpath_rw'],
1919
test_suite = 'tests',
20-
install_requires = [ 'ply', 'decorator' ],
20+
install_requires = [ 'ply', 'decorator', 'six' ],
2121
)

tests/test_jsonpath.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,13 @@ def test_index(self):
3131

3232
def test_slice(self):
3333
self.check_cases([('[*]', [1, 2, 3], [1, 2, 3]),
34+
('[*]', xrange(1, 4), [1, 2, 3]),
3435
('[1:]', [1, 2, 3, 4], [2, 3, 4]),
3536
('[:2]', [1, 2, 3, 4], [1, 2])])
3637

3738
def test_child(self):
3839
self.check_cases([('foo.baz', {'foo': {'baz': 3}}, [3]),
40+
('foo.baz', {'foo': {'baz': [3]}}, [[3]]),
3941
('foo.baz.bizzle', {'foo': {'baz': {'bizzle': 5}}}, [5])])
4042

4143
def test_descendants(self):

0 commit comments

Comments
 (0)