Skip to content

Support for collections.abc classes #20

@niflostancu

Description

@niflostancu

jsonpath2 version

0.1.0

Scenario:

I have a tree consisting of custom node classes representing list / map containers.
I use the collections.abc.Sequence and collections.abc.Mapping base classes to do this.
Unfortunately, jsonpath2 uses hardcoded conditions like isinstance(value, list) and isinstance(value, dict) when evaluating the expressions and my custom objects simply won't pass it.

Steps to Reproduce:

from collections.abc import Mapping
from jsonpath2.path import Path

class MyDict(Mapping):
    def __init__(self, data=None):
        self._data = data if data is not None else {}
    def __getitem__(self, key):
        return self._data[key]
    def __iter__(self):
        return self._data.__iter__()
    def __len__(self):
        return len(self._data)

d = {"hello": {"world": "itsme!"}}
myd = MyDict({"hello": MyDict({"world": "itsme!"})})
p = Path.parse_str('$["hello"]["world"]')

print("Dict:", list(map(lambda match_data: match_data.current_value, p.match(d))))
print("MyDict:", list(map(lambda match_data: match_data.current_value, p.match(myd))))
print("isinstance(dict, Mapping):", isinstance(d, Mapping))
print("isinstance(MyDict, dict):", isinstance(myd, dict))

The analogous goes for Sequence versus list.

Expected Result:

Using the collections.abc module is the official recommandation for implementing standard collection semantics. Expressions like myd["hello"]["world"] work as expected on them.
JSONPath2 should support it, too.

Actual Result:

Dict: ['itsme!']
MyDict: []
isinstance(dict, Mapping): True
isinstance(MyDict, dict): False

So a simple replace of isinstance(value, dict) with isinstance(value, Mapping) should suffice. Same for list to Sequence.
Can I come with a pull request for this?
Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions