Skip to content

Commit c0449e0

Browse files
committed
Handle add with path="". Fixes #188
1 parent 01d25e9 commit c0449e0

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

v5/patch.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -729,6 +729,32 @@ func (p Patch) add(doc *container, op Operation, options *ApplyOptions) error {
729729
return errors.Wrapf(ErrMissing, "add operation failed to decode path")
730730
}
731731

732+
// special case, adding to empty means replacing the container with the value given
733+
if path == "" {
734+
val := op.value()
735+
736+
var pd container
737+
if (*val.raw)[0] == '[' {
738+
pd = &partialArray{
739+
self: val,
740+
}
741+
} else {
742+
pd = &partialDoc{
743+
self: val,
744+
}
745+
}
746+
747+
err := json.Unmarshal(*val.raw, pd)
748+
749+
if err != nil {
750+
return err
751+
}
752+
753+
*doc = pd
754+
755+
return nil
756+
}
757+
732758
if options.EnsurePathExistsOnAdd {
733759
err = ensurePathExists(doc, path, options)
734760

v5/patch_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,6 +592,20 @@ var Cases = []Case{
592592
false,
593593
false,
594594
},
595+
{
596+
`{}`,
597+
`[{"op":"add","path":"","value":{"foo":"bar"}}]`,
598+
`{"foo": "bar"}`,
599+
false,
600+
false,
601+
},
602+
{
603+
`[]`,
604+
`[{"op":"add","path":"","value":{"foo":"bar"}}, {"op": "add", "path": "/qux", "value": 1}]`,
605+
`{"foo": "bar", "qux": 1}`,
606+
false,
607+
false,
608+
},
595609
}
596610

597611
type BadCase struct {

0 commit comments

Comments
 (0)