Skip to content

Commit 2825f82

Browse files
committed
add str() method
1 parent 1ba2ab3 commit 2825f82

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

jsonpath_ng/ext/parser.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,8 @@ def p_jsonpath_named_operator(self, p):
100100
p[0] = _string.Split(p[1])
101101
elif p[1].startswith("sub("):
102102
p[0] = _string.Sub(p[1])
103+
elif p[1].startswith("str("):
104+
p[0] = _string.Str(p[1])
103105
else:
104106
super(ExtentedJsonPathParser, self).p_jsonpath_named_operator(p)
105107

jsonpath_ng/ext/string.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
SUB = re.compile("sub\(/(.*)/,\s+(.*)\)")
1919
SPLIT = re.compile("split\((.),\s+(\d+),\s+(\d+|-1)\)")
20+
STR = re.compile("str\(\)")
2021

2122

2223
class DefintionInvalid(Exception):
@@ -87,3 +88,30 @@ def __repr__(self):
8788

8889
def __str__(self):
8990
return '`%s`' % self.method
91+
92+
93+
class Str(This):
94+
"""String converter
95+
96+
Concrete syntax is '`str()`'
97+
"""
98+
99+
def __init__(self, method=None):
100+
m = STR.match(method)
101+
if m is None:
102+
raise DefintionInvalid("%s is not valid" % method)
103+
self.method = method
104+
105+
def find(self, datum):
106+
datum = DatumInContext.wrap(datum)
107+
value = str(datum.value)
108+
return [DatumInContext.wrap(value)]
109+
110+
def __eq__(self, other):
111+
return (isinstance(other, Str) and self.method == other.method)
112+
113+
def __repr__(self):
114+
return '%s(%r)' % (self.__class__.__name__, self.method)
115+
116+
def __str__(self):
117+
return '`str()`'

tests/test_jsonpath_rw_ext.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,11 @@ class Testjsonpath_ng_ext(testscenarios.WithScenarios,
276276
data={'payload': "foo+bar"},
277277
target=["repl"]
278278
)),
279-
279+
('str1', dict(
280+
string='payload.`str()`',
281+
data={'payload': 1},
282+
target=["1"]
283+
)),
280284
('split1', dict(
281285
string='payload.`split(-, 2, -1)`',
282286
data={'payload': "foo-bar-cat-bow"},

0 commit comments

Comments
 (0)