Search code examples
pythonobjectpath

ObjectPath: trouble with "in" operator


I am learning ObjectPath for python and have found out, e.g., how to do an exact match on an attribute:

>>> import objectpath
>>>
>>> tree = objectpath.Tree({'doc': {'title': 'Purple is Best Color'}})
>>>
>>> tree.execute('$..*[@.title is "Purple is Best Color"]').next()
{'title': 'Purple is Best Color'}

This makes sense to me; I want to start from the root ($) and recursively (..) find all (*) items (@) for which title == "Purple is Best Color". And it works!

But then I try something similar with the in operator:

>>> tree.execute('$..*["Purple" in @.title]').next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Huh? Seemed like a natural way to tweak the condition, but it's not quite right.

In the manual, I read that in checks if the result of the left side of expression is in array, object or string, and that in objects, keys are matched. (maybe that's my issue, but not sure quite what it means here). I think that my current @ is indeed a string...?

Considering the above, what could I be missing here?


Solution

  • Interestingly enough, explicitly converting Purple to string works:

    $..*[str("Purple") in @.title]
    

    Created an issue at ObjectPath issue tracker: