h2non / jsonpath-ng

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

jsonpath division error #17

Open tillschumann opened 6 years ago

tillschumann commented 6 years ago

Hi, Great Library! But unfortunately, I get an error trying to use the division operator.

Example:

from jsonpath_ng.ext import parse
jsonpath_expr = parse("A / 80", debug=True)

Traceback (most recent call last):
  File "test_jsonpath.py", line 2, in <module>
    jsonpath_expr = parse("A / 80", debug=True)
  File "/usr/local/lib/python2.7/site-packages/jsonpath_ng/ext/parser.py", line 170, in parse
    return ExtentedJsonPathParser(debug=debug).parse(path)
  File "/usr/local/lib/python2.7/site-packages/jsonpath_ng/parser.py", line 32, in parse
    return self.parse_token_stream(lexer.tokenize(string))
  File "/usr/local/lib/python2.7/site-packages/jsonpath_ng/parser.py", line 55, in parse_token_stream
    return new_parser.parse(lexer = IteratorToTokenStream(token_iterator))
  File "/usr/local/lib/python2.7/site-packages/ply/yacc.py", line 333, in parse
    return self.parseopt_notrack(input, lexer, debug, tracking, tokenfunc)
  File "/usr/local/lib/python2.7/site-packages/ply/yacc.py", line 1201, in parseopt_notrack
    tok = call_errorfunc(self.errorfunc, errtoken, self)
  File "/usr/local/lib/python2.7/site-packages/ply/yacc.py", line 192, in call_errorfunc
    r = errorfunc(token)
  File "/usr/local/lib/python2.7/site-packages/jsonpath_ng/parser.py", line 69, in p_error
    raise Exception('Parse error at %s:%s near token %s (%s)' % (t.lineno, t.col, t.value, t.type))
Exception: Parse error at 1:2 near token / (SORT_DIRECTION)

Am I using it wrong? I tried to debug the code, but I couldn't figure out why it does not work.

Thanks a lot for any hints! Best, Till

michasng commented 3 years ago

I have the same issue and my workaround so far has been to multiply by the inverse. So instead of A / 80, I do A * 0.0125, because 1/80=0.0125. However this will also result in a parse error, when both sides are just numberic values, as in 2 * 0.0125.

daloe commented 3 years ago

Same issue, my workaround is to change the regex used in t_SORT_DIRECTION. It probably breaks features using t_SORT_DIRECTION.

from jsonpath_ng.ext import parse
from jsonpath_ng.ext.parser import ExtendedJsonPathLexer
ExtendedJsonPathLexer.t_SORT_DIRECTION.__doc__ = r',?\s*(//|\\)'  #  replace r',?\s*(/|\\)' by r',?\s*(//|\\)'

jsonpath_expr = parse('$.A / 80', debug=True)
jsonpath_expr.find({'A': 160})
[DatumInContext(value=2.0, path=This(), context=None)]