From a0bfd48d36b315baceee79a559c36c8144ccc231 Mon Sep 17 00:00:00 2001 From: Joao Andrade Date: Sat, 13 Feb 2021 20:29:16 +0000 Subject: [PATCH] Support nested array wildcard deletion --- gabs.go | 11 +++++++++++ gabs_test.go | 13 +++++++++++++ 2 files changed, 24 insertions(+) diff --git a/gabs.go b/gabs.go index c75e8de..85f418d 100644 --- a/gabs.go +++ b/gabs.go @@ -463,6 +463,17 @@ func (g *Container) Delete(hierarchy ...string) error { if len(hierarchy) < 2 { return errors.New("unable to delete array index at root of path") } + + // delete within one nested wildcard level + if hierarchy[1] == "*" { + for i := range array { + if obj, ok := array[i].(map[string]interface{}); ok { + delete(obj, target) + } + } + return nil + } + index, err := strconv.Atoi(target) if err != nil { return fmt.Errorf("failed to parse array index '%v': %v", target, err) diff --git a/gabs_test.go b/gabs_test.go index bcd0cd7..529cbcd 100644 --- a/gabs_test.go +++ b/gabs_test.go @@ -669,6 +669,19 @@ func TestDeletesWithArrays(t *testing.T) { if actual := jsonParsed.String(); actual != expected { t.Errorf("Unexpected result from array deletes: %v != %v", actual, expected) } + + jsonParsed, err = ParseJSON([]byte(rawJSON)) + if err != nil { + t.Fatal(err) + } + if err = jsonParsed.Delete("outter", "*", "bar"); err != nil { + t.Error(err) + } + + expected = `{"outter":[{"foo":{"value1":10,"value2":22,"value3":32}},{"baz":{"value1":null,"value2":null,"value3":null}}]}` + if actual := jsonParsed.String(); actual != expected { + t.Errorf("Unexpected result from array deletes: %v != %v", actual, expected) + } } func TestExamples(t *testing.T) {