Skip to content

Commit 81820e2

Browse files
committed
Implemented split() function
1 parent 262a822 commit 81820e2

File tree

1 file changed

+44
-6
lines changed

1 file changed

+44
-6
lines changed

jmespath/functions.py

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -347,17 +347,55 @@ def _pad_impl(self, func, padding):
347347
{'type': 'string'},
348348
{'type': 'number', 'optional': True})
349349
def _func_replace(self, text, search, replacement, count = None):
350-
if count != None:
351-
if int(count) != count or int(count) < 0:
352-
raise exceptions.JMESPathError(
353-
'syntax-error: replace() expects $count to be a '
354-
'non-negative integer, but received {} instead.'
355-
.format(count))
350+
self._ensure_non_negative_optional_integer(
351+
'replace',
352+
'count',
353+
count)
356354

357355
if count != None:
358356
return text.replace(search, replacement, int(count))
359357
return text.replace(search, replacement)
360358

359+
@signature(
360+
{'type': 'string'},
361+
{'type': 'string'},
362+
{'type': 'number', 'optional': True})
363+
def _func_split(self, text, search, count = None):
364+
self._ensure_non_negative_optional_integer(
365+
'split',
366+
'count',
367+
count)
368+
369+
if len(search) == 0:
370+
chars = list(text)
371+
if count == None:
372+
return chars
373+
374+
head = [c for c in chars[:count]]
375+
tail = [''.join(chars[count:])]
376+
return head + tail
377+
378+
if count != None:
379+
return text.split(search, count)
380+
return text.split(search)
381+
382+
def _ensure_non_negative_optional_integer(
383+
self,
384+
func_name,
385+
param_name,
386+
param_value):
387+
388+
if param_value != None:
389+
if int(param_value) != param_value or int(param_value) < 0:
390+
raise exceptions.JMESPathError(
391+
'syntax-error: replace() expects ${} to be a '
392+
'non-negative integer, but received {} instead.'
393+
.format(
394+
func_name,
395+
param_name,
396+
param_name
397+
))
398+
361399
@signature({'type': 'string'}, {'type': 'string', 'optional': True})
362400
def _func_trim(self, text, chars = None):
363401
if chars == None or len(chars) == 0:

0 commit comments

Comments
 (0)