Skip to content

Commit c645ff4

Browse files
committed
Handle add with path="". Fixes #188
1 parent b5e20d4 commit c645ff4

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
@@ -773,6 +773,32 @@ func (p Patch) add(doc *container, op Operation, options *ApplyOptions) error {
773773
return errors.Wrapf(ErrMissing, "add operation failed to decode path")
774774
}
775775

776+
// special case, adding to empty means replacing the container with the value given
777+
if path == "" {
778+
val := op.value()
779+
780+
var pd container
781+
if (*val.raw)[0] == '[' {
782+
pd = &partialArray{
783+
self: val,
784+
}
785+
} else {
786+
pd = &partialDoc{
787+
self: val,
788+
}
789+
}
790+
791+
err := json.Unmarshal(*val.raw, pd)
792+
793+
if err != nil {
794+
return err
795+
}
796+
797+
*doc = pd
798+
799+
return nil
800+
}
801+
776802
if options.EnsurePathExistsOnAdd {
777803
err = ensurePathExists(doc, path, options)
778804

v5/patch_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -599,6 +599,20 @@ var Cases = []Case{
599599
false,
600600
false,
601601
},
602+
{
603+
`{}`,
604+
`[{"op":"add","path":"","value":{"foo":"bar"}}]`,
605+
`{"foo": "bar"}`,
606+
false,
607+
false,
608+
},
609+
{
610+
`[]`,
611+
`[{"op":"add","path":"","value":{"foo":"bar"}}, {"op": "add", "path": "/qux", "value": 1}]`,
612+
`{"foo": "bar", "qux": 1}`,
613+
false,
614+
false,
615+
},
602616
}
603617

604618
type BadCase struct {

0 commit comments

Comments
 (0)