Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow negative segment indexing on split extension #95

Open
ElSaico opened this issue Dec 3, 2021 · 0 comments · May be fixed by #99
Open

Allow negative segment indexing on split extension #95

ElSaico opened this issue Dec 3, 2021 · 0 comments · May be fixed by #99

Comments

@ElSaico
Copy link

ElSaico commented Dec 3, 2021

Currently, the split extension only allows positive indexes for its segments. However, I want to pick the very last segment, and their quantity is arbitrary.

My workaround so far is extending the parser just for a small regex tweak:

from jsonpath_ng.ext.parser import ExtentedJsonPathParser
from jsonpath_ng.ext.string import Split


SPLIT_NEGATIVE_INDEXABLE = re.compile(r"split\((.),\s+(-?\d+),\s+(\d+|-1)\)")


class SplitNegativeIndexable(Split):
    def __init__(self, method=None):
        m = SPLIT_NEGATIVE_INDEXABLE.match(method)
        self.char = m.group(1)
        self.segment = int(m.group(2))
        self.max_split = int(m.group(3))
        self.method = method


class JsonPathParser(ExtentedJsonPathParser):
    """we need a docstring here otherwise jsonpath-rw starts grumbling"""

    def p_jsonpath_named_operator(self, p):
        "jsonpath : NAMED_OPERATOR"
        if p[1].startswith("split("):
            p[0] = SplitNegativeIndexable(p[1])
        else:
            super().p_jsonpath_named_operator(p)

I can send a proper PR once I finish working for today.

@ElSaico ElSaico linked a pull request Mar 11, 2022 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants