evanphx/json-patch

add on `null` does not work anymore ?

Closed this issue · 10 comments

Looks like applying an add patch to null now panics: https://go.dev/play/p/qo2WNSqwpYZ

package main

import (
	"fmt"

	jsonpatch "github.com/evanphx/json-patch/v5"
)

func main() {
	original := []byte(`null`)
	patchJSON := []byte(`[{"op": "add", "path": "/version", "value": "0.2.0"}]`)
	patch, err := jsonpatch.DecodePatch(patchJSON)
	if err != nil {
		panic(err)
	}
	options := &jsonpatch.ApplyOptions{EnsurePathExistsOnAdd: true}
	modified, err := patch.ApplyWithOptions(original, options)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Original document:\n%s\n", original)
	fmt.Printf("Modified document:\n%s\n", modified)
}
panic: assignment to entry in nil map

goroutine 1 [running]:
github.com/evanphx/json-patch/v5.(*partialDoc).set(...)
	/tmp/gopath2668474575/pkg/mod/github.com/evanphx/json-patch/v5@v5.8.1/patch.go:570
github.com/evanphx/json-patch/v5.(*partialDoc).add(0xc0000161b0, {0xc000012120, 0x7}, 0xc0000600e0, 0x496328?)
	/tmp/gopath2668474575/pkg/mod/github.com/evanphx/json-patch/v5@v5.8.1/patch.go:575 +0x176
github.com/evanphx/json-patch/v5.Patch.add({0xc000012028?, 0x4?, 0x4?}, 0xc000104e60, 0xc0000161b0?, 0xc00001a078)
	/tmp/gopath2668474575/pkg/mod/github.com/evanphx/json-patch/v5@v5.8.1/patch.go:781 +0x25e
github.com/evanphx/json-patch/v5.Patch.ApplyIndentWithOptions({0xc000060040?, 0x1, 0x4}, {0xc000012028, 0x4, 0x4}, {0x0, 0x0}, 0x60?)
	/tmp/gopath2668474575/pkg/mod/github.com/evanphx/json-patch/v5@v5.8.1/patch.go:1221 +0x2d9
github.com/evanphx/json-patch/v5.Patch.ApplyWithOptions(...)
	/tmp/gopath2668474575/pkg/mod/github.com/evanphx/json-patch/v5@v5.8.1/patch.go:1174
main.main()
	/tmp/sandbox724842672/prog.go:17 +0x105

Program exited.

Shouldn't panic, that's a bug I'll fix now. But I don't think it's valid either.

Thanks, it used to work in 5.7.0 and below (at least with EnsurePathExistsOnAdd: true)

@eddycharly what did it do? Why were you using it?

Looks like in v5.7.0, it returned an error about the json document...

Yes, in v5.7.0 it returned an error failed to patch resource: unexpected JSON token in document node: <nil>.

kk, I'll have a 5.8.2 out shortly that fixes this.

@evanphx are you still planing a fix release soon ?

shall I give it a try and open a PR ? would that help ?

Sorry for the delay, dealing with this today.

5.9.0 is out now with the fix!

Thanks, trying it out !