From a8fc969a3411003c9a2925be033b2a468df0de61 Mon Sep 17 00:00:00 2001 From: acejilam Date: Thu, 10 Aug 2023 19:32:47 +0800 Subject: [PATCH] Fix: null jsonpath serialization Signed-off-by: acejilam Kubernetes-commit: 9646ae5a9efb0eee7ac15577d113699700233017 --- util/jsonpath/jsonpath.go | 3 +++ util/jsonpath/jsonpath_test.go | 4 +++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/util/jsonpath/jsonpath.go b/util/jsonpath/jsonpath.go index 49ecd146..86a3d6dd 100644 --- a/util/jsonpath/jsonpath.go +++ b/util/jsonpath/jsonpath.go @@ -573,6 +573,9 @@ func (j *JSONPath) evalToText(v reflect.Value) ([]byte, error) { if !ok { return nil, fmt.Errorf("can't print type %s", v.Type()) } + if iface == nil { + return []byte("null"), nil + } var buffer bytes.Buffer fmt.Fprint(&buffer, iface) return buffer.Bytes(), nil diff --git a/util/jsonpath/jsonpath_test.go b/util/jsonpath/jsonpath_test.go index 6473d259..18fd8c8f 100644 --- a/util/jsonpath/jsonpath_test.go +++ b/util/jsonpath/jsonpath_test.go @@ -301,7 +301,8 @@ func TestJSONInput(t *testing.T) { {"id": "i3", "x": 8, "y": 3 }, {"id": "i4", "x": -6, "y": -1 }, {"id": "i5", "x": 0, "y": 2, "z": 1 }, - {"id": "i6", "x": 1, "y": 4 } + {"id": "i6", "x": 1, "y": 4 }, + {"id": "i7", "x": null, "y": 4 } ]`) var pointsData interface{} err := json.Unmarshal(pointsJSON, &pointsData) @@ -311,6 +312,7 @@ func TestJSONInput(t *testing.T) { pointsTests := []jsonpathTest{ {"exists filter", "{[?(@.z)].id}", pointsData, "i2 i5", false}, {"bracket key", "{[0]['id']}", pointsData, "i1", false}, + {"nil value", "{[-1]['x']}", pointsData, "null", false}, } testJSONPath(pointsTests, false, t) }