h2non / jsonpath-ng

Finally, a JSONPath implementation for Python that aims to be standard compliant. That's all. Enjoy!
Apache License 2.0
572 stars 85 forks source link

Allow negative segment indexing on split extension #95

Open ElSaico opened 2 years ago

ElSaico commented 2 years ago

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.