diff --git a/jmespath/functions.py b/jmespath/functions.py index 11ab56a..a026001 100644 --- a/jmespath/functions.py +++ b/jmespath/functions.py @@ -259,6 +259,34 @@ def _func_max(self, arg): else: return None + @signature({'types': ['object'], "variadic": True}, {'types': ['boolean']}) + def _func_remove_null(self, obj, recursive): + if recursive: + return self._func_remove_recursive(obj, None) + else: + return self._func_remove(obj, None) + + @signature({'types': ['object'], "variadic": True}, {'types': ['boolean']}) + def _func_remove_empty(self, obj, recursive): + if recursive: + return self._func_remove_recursive(obj, None, '') + else: + return self._func_remove(obj, None, '') + + def _func_remove(self, obj, *args): + return {k: v for k, v in obj.items() if not v in list(args)} + + def _func_remove_recursive(self, obj, *args): + ret_dict = {} + for k in obj: + if not obj[k] in list(args): + ret_dict[k] = obj[k] + + if isinstance(obj[k], dict): + ret_dict[k] = self._func_remove_recursive(obj[k], *args) + + return ret_dict + @signature({"types": ["object"], "variadic": True}) def _func_merge(self, *arguments): merged = {} diff --git a/tests/compliance/functions.json b/tests/compliance/functions.json index 7b55445..7b5d69c 100644 --- a/tests/compliance/functions.json +++ b/tests/compliance/functions.json @@ -12,9 +12,38 @@ "empty_list": [], "empty_hash": {}, "objects": {"foo": "bar", "bar": "baz"}, + "objectsNull": {"foo": "bar", "bar": null}, + "objectsEmpty": {"foo": "", "bar": null, "baz": "baz"}, + "objectsEmptyNested": {"foo": "", "bar": null, "baz": {"foo": "", "bar": "bar", "foe": null}}, + "objectsNullNested": {"foo": "bar", "bar": null, "baz": { "bar": null, "foo": "foo"}}, "null_key": null }, "cases": [ + { + "expression": "remove_empty(objectsEmptyNested, `false`)", + "result": {"baz": {"foo": "", "bar": "bar", "foe": null}} + }, + + { + "expression": "remove_empty(objectsEmptyNested, `true`)", + "result": {"baz": {"bar": "bar"}} + }, + { + "expression": "remove_empty(objectsEmpty, `false`)", + "result": {"baz": "baz"} + }, + { + "expression": "remove_null(objectsNull, `false`)", + "result": {"foo": "bar"} + }, + { + "expression": "remove_null(objectsNullNested, `false`)", + "result": {"foo": "bar", "baz": { "bar": null, "foo": "foo"}} + }, + { + "expression": "remove_null(objectsNullNested, `true`)", + "result": {"foo": "bar", "baz": {"foo": "foo"}} + }, { "expression": "abs(foo)", "result": 1 @@ -189,7 +218,7 @@ }, { "expression": "length(@)", - "result": 12 + "result": 16 }, { "expression": "length(strings[0])",