Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removal Method for Arrays #62

Open
Rhiannon-Udall opened this issue Dec 16, 2022 · 0 comments
Open

Removal Method for Arrays #62

Rhiannon-Udall opened this issue Dec 16, 2022 · 0 comments

Comments

@Rhiannon-Udall
Copy link

In my project I found it necessary to sometimes remove elements (though not objects) from json arrays. I was able to do this by adding a separate merge strategy which takes a negative image of an array, such that, e.g.

test  = {
"AnArray":["An element", "A second element"]
}

removal = {
"AnArray":["An element"]
}

new = merger.merge(test, removal) 

new  = {
"AnArray":["A second element"]
}

The code for this is quite similar to that for append:

class RemoveStrategy(ArrayStrategy):
        def _merge(
            self, walk, base, head, schema, sortByRef=None, sortReverse=None, **kwargs
        ):
            new_array = []
            for array_element in base.val:
                if array_element not in head.val:
                    new_array.append(array_element)

            base.val = new_array

            self.sort_array(walk, base, sortByRef, sortReverse)

            return base

        def get_schema(self, walk, schema, **kwargs):
            schema.val.pop("maxItems", None)
            schema.val.pop("uniqueItems", None)

            return schema

I am happy to just have this within my project, but I wished to offer that if there is interest in adding this feature to the main package then I can write up the requisite tests and doc entry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant