Skip to content

Commit

Permalink
Handle add with path="". Fixes #188
Browse files Browse the repository at this point in the history
  • Loading branch information
evanphx committed Jan 11, 2024
1 parent 01d25e9 commit c0449e0
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
26 changes: 26 additions & 0 deletions v5/patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -729,6 +729,32 @@ func (p Patch) add(doc *container, op Operation, options *ApplyOptions) error {
return errors.Wrapf(ErrMissing, "add operation failed to decode path")
}

// special case, adding to empty means replacing the container with the value given
if path == "" {
val := op.value()

var pd container
if (*val.raw)[0] == '[' {
pd = &partialArray{
self: val,
}
} else {
pd = &partialDoc{
self: val,
}
}

err := json.Unmarshal(*val.raw, pd)

if err != nil {
return err
}

*doc = pd

return nil
}

if options.EnsurePathExistsOnAdd {
err = ensurePathExists(doc, path, options)

Expand Down
14 changes: 14 additions & 0 deletions v5/patch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,20 @@ var Cases = []Case{
false,
false,
},
{
`{}`,
`[{"op":"add","path":"","value":{"foo":"bar"}}]`,
`{"foo": "bar"}`,
false,
false,
},
{
`[]`,
`[{"op":"add","path":"","value":{"foo":"bar"}}, {"op": "add", "path": "/qux", "value": 1}]`,
`{"foo": "bar", "qux": 1}`,
false,
false,
},
}

type BadCase struct {
Expand Down

0 comments on commit c0449e0

Please sign in to comment.