add a "Delete" method that only works on maps for now
diff --git a/pointer.go b/pointer.go
index 06f1918..62ed714 100644
--- a/pointer.go
+++ b/pointer.go
@@ -90,6 +90,13 @@
}
+// Uses the pointer to delete a value from a JSON document (only works on maps/objects right now, not arrays)
+func (p *JsonPointer) Delete(document interface{}) (interface{}, reflect.Kind, error) {
+ is := &implStruct{mode: "DEL", inDocument: document}
+ p.implementation(is)
+ return is.getOutNode, is.getOutKind, is.outError
+}
+
// Both Get and Set functions use the same implementation to avoid code duplication
func (p *JsonPointer) implementation(i *implStruct) {
@@ -118,6 +125,8 @@
node = v[decodedToken]
if isLastToken && i.mode == "SET" {
v[decodedToken] = i.setInValue
+ } else if isLastToken && i.mode =="DEL" {
+ delete(v,decodedToken)
}
} else {
i.outError = fmt.Errorf("Object has no key '%s'", decodedToken)
diff --git a/pointer_test.go b/pointer_test.go
index 9e66d51..ab8a7cd 100644
--- a/pointer_test.go
+++ b/pointer_test.go
@@ -245,3 +245,43 @@
}
}
+
+func TestDelMapNode(t *testing.T) {
+ jsonText := `{
+ "a":[{"b": 1, "c": 2}],
+ "d": {
+ "z" : {
+ "v" : {
+ "name" : "donald mcbobble",
+ "occupation" : "corporate overlord"
+ }
+ }
+ }
+ }`
+
+ var jsonDocument map[string]interface{}
+ json.Unmarshal([]byte(jsonText), &jsonDocument)
+
+ in := "/d/z/v/occupation"
+ p, err := NewJsonPointer(in)
+ if err != nil {
+ t.Errorf("NewJsonPointer(%v) error %v", in, err.Error())
+ }
+
+ _, _, err = p.Delete(jsonDocument)
+ if err != nil {
+ t.Errorf("Delete(%v) error %v", in, err.Error())
+ }
+
+ var d map[string]interface{} = jsonDocument["d"].(map[string]interface{})
+ var z map[string]interface{} = d["z"].(map[string]interface{})
+ var v map[string]interface{} = z["v"].(map[string]interface{})
+
+ if v["name"] != "donald mcbobble" {
+ t.Errorf("Delete (%s) failed: caused an unexpected side effect")
+ }
+
+ if _, present := v["occupation"]; present {
+ t.Errorf("Delete (%s) failed: key is still present in the map", in)
+ }
+}