avian2 / jsonmerge

Merge a series of JSON documents.
MIT License
214 stars 25 forks source link

Removal Method for Arrays #62

Open Rhiannon-Udall opened 1 year ago

Rhiannon-Udall commented 1 year ago

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.