yudai / gojsondiff

Go JSON Diff
Other
535 stars 81 forks source link

Text diff is incorrectly deserialized #31

Open alexmt opened 5 years ago

alexmt commented 5 years ago

The text diff is incorrectly deserialized if diff consists of text insert + text delete. Golang snippet below demonstrates the problem.

package diff

import (
    "encoding/json"
    "os"

    "github.com/yudai/gojsondiff"
    "github.com/yudai/gojsondiff/formatter"
    "golang.org/x/crypto/ssh/terminal"
)

func main() {
    left := make(map[string]interface{})
    right := make(map[string]interface{})
    _ = json.Unmarshal([]byte(`{ "data": { "int": 1, "string": "gcr.io/heptio-images/ks-guestbook-demo:0.1" } }`), &left)
    _ = json.Unmarshal([]byte(`{ "data": { "int": 2, "string": "gcr.io/heptio-images/ks-guestbook-demo:0.2" } }`), &right)
    jsonFmt := formatter.NewDeltaFormatter()

    diff := gojsondiff.New().CompareObjects(left, right)
    jsonDiff, _ := jsonFmt.Format(diff)

    asciiFmt := formatter.NewAsciiFormatter(left, formatter.AsciiFormatterConfig{Coloring: terminal.IsTerminal(int(os.Stdout.Fd()))})
    formatted, _ := asciiFmt.Format(diff)
    println(formatted)

    diffUnmarshaller := gojsondiff.NewUnmarshaller()
    diff, _ = diffUnmarshaller.UnmarshalString(jsonDiff)

    formatted, _ = asciiFmt.Format(diff)
    println(formatted)
}

Program prints ascii formatted diff before and after deserialization. Output below demonstrates that after deserialization string field value is printed as null.

 {
   "data": {
-    "int": 1,
+    "int": 2,
-    "string": "gcr.io/heptio-images/ks-guestbook-demo:0.1"
+    "string": "gcr.io/heptio-images/ks-guestbook-demo:0.2"
   }
 }

 {
   "data": {
-    "int": 1,
+    "int": 2,
-    "string": null
+    "string": null
   }
 }