adriank / ObjectPath

The agile query language for semi-structured data
http://objectpath.org
MIT License
380 stars 93 forks source link

Can't filter selections on root node #43

Closed pkerpedjiev closed 8 years ago

pkerpedjiev commented 8 years ago

Consider the correctly working code below. It simply selects the elements where x<2.

>>> a = {"data": [{'x': 1}, {'x':2}]}
>>> tree = objectpath.Tree(a)
>>> list(tree.execute('$.data[@.x < 2]'))
[{'x': 1}]

Now if we remove data and make the list the root node, it doesn't work:

>>> a = [{'x': 1}, {'x':2}]
>>> tree = objectpath.Tree(a)
>>> list(tree.execute('$[@.x < 2]'))
[{'x': 1}, {'x': 2}]

Is there a reason why this is so? Should it be so? Wouldn't it make conceptual sense to be able to do the same filters on the root node as on child nodes?

adriank commented 8 years ago

$ needs to be postponed by . or .. and then attribute name or wildcard.

list(tree.execute('$.*[@.x < 2]')) should work. :)

pkerpedjiev commented 8 years ago

Thanks for the quick response! It does indeed work.

But shouldn't the version I posted also work?

If $.data[@.x < 2] refers to all entries in $.data where x < 2, then shouldn't $[@.x < 2] logically refer to all entries in $ where x < 2?

adriank commented 8 years ago

For me $[@ looks like brainfuck. :)

If you like to change this behavior go here: https://github.com/adriank/ObjectPath/blob/master/objectpath/core/parser.py#L274 and comment lines: 274, 276-278. Namespaces doesn't work ATM so nothing will break.