diff --git a/node_mutations.go b/node_mutations.go index a272c72..0d5bf72 100644 --- a/node_mutations.go +++ b/node_mutations.go @@ -184,7 +184,9 @@ func (n *Node) clone() *Node { dirty: n.dirty, } for key, value := range n.children { - node.children[key] = value.clone() + clone := value.clone() + clone.parent = node + node.children[key] = clone } return node } diff --git a/node_mutations_test.go b/node_mutations_test.go index 47b11c7..59703bd 100644 --- a/node_mutations_test.go +++ b/node_mutations_test.go @@ -1380,6 +1380,7 @@ func TestNode_Clone(t *testing.T) { null := NullNode("") array := ArrayNode("", []*Node{node, null}) object := ObjectNode("", map[string]*Node{"array": array}) + objectWithObject := ObjectNode("", map[string]*Node{"object": object}) tests := []struct { name string @@ -1406,6 +1407,11 @@ func TestNode_Clone(t *testing.T) { node: object, json: `{"array":[1.1,null]}`, }, + { + name: "objectWithObject", + node: objectWithObject, + json: `{"object":{"array":[1.1,null]}}`, + }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -1427,10 +1433,23 @@ func TestNode_Clone(t *testing.T) { } else if string(base) != test.json { t.Errorf("Marshal() base not match: \nExpected: %s\nActual: %s", test.json, base) } + + validateParent(t, clone) }) } } +// validateParent checks if all children have the correct parent, recursively. +func validateParent(t *testing.T, node *Node) { + for _, child := range node.Inheritors() { + if child.Parent() != node { + t.Errorf("Inheritor.Parent() != node") + } + + validateParent(t, child) + } +} + func ExampleNode_Clone() { root := Must(Unmarshal(jsonPathTestData)) nodes, _ := root.JSONPath("$..price")