From ad271d568b713ad381ad6751cd8b950eade78d98 Mon Sep 17 00:00:00 2001 From: Just-maple <31134320+Just-maple@users.noreply.github.com> Date: Fri, 1 Mar 2024 06:55:22 +0800 Subject: [PATCH] feat: handle escape and null value (#419) --- jsonwriter/writer.go | 20 ++++++++------------ jsonwriter/writer_test.go | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/jsonwriter/writer.go b/jsonwriter/writer.go index cc0eaccb..7da769c5 100644 --- a/jsonwriter/writer.go +++ b/jsonwriter/writer.go @@ -18,19 +18,15 @@ import ( "bytes" "errors" "fmt" - "strings" + "strconv" "gopkg.in/yaml.v3" ) -const indentation = " " - -// basic escaping, will need to be improved or replaced -func escape(s string) string { - s = strings.Replace(s, "\n", "\\n", -1) - s = strings.Replace(s, "\"", "\\\"", -1) - return s -} +const ( + indentation = " " + null = "null" +) type writer struct { b bytes.Buffer @@ -85,15 +81,15 @@ func (w *writer) writeScalar(node *yaml.Node, indent string) { } switch node.Tag { case "!!str": - w.writeString("\"") - w.writeString(escape(node.Value)) - w.writeString("\"") + w.writeString(strconv.Quote(node.Value)) case "!!int": w.writeString(node.Value) case "!!float": w.writeString(node.Value) case "!!bool": w.writeString(node.Value) + case "!!null": + w.writeString(null) } } diff --git a/jsonwriter/writer_test.go b/jsonwriter/writer_test.go index b714e609..28f28a29 100644 --- a/jsonwriter/writer_test.go +++ b/jsonwriter/writer_test.go @@ -37,6 +37,8 @@ func TestMarshal(t *testing.T) { scalarBoolTestCase(), scalarFloatTestCase(), scalarIntTestCase(), + scalarStringTestCase(), + scalarNullTestCase(), sequenceStringArrayTestCase(), sequenceBoolArrayTestCase(), sequenceFloatArrayTestCase(), @@ -88,6 +90,22 @@ func scalarFloatTestCase() *MarshalTestCase { } } +func scalarStringTestCase() *MarshalTestCase { + return &MarshalTestCase{ + Name: "scalar string", + Node: compiler.NewScalarNodeForString("a\\b\nc\""), + Expected: "\"a\\\\b\\nc\\\"\"\n", + } +} + +func scalarNullTestCase() *MarshalTestCase { + return &MarshalTestCase{ + Name: "scalar null", + Node: compiler.NewNullNode(), + Expected: "null\n", + } +} + func scalarIntTestCase() *MarshalTestCase { return &MarshalTestCase{ Name: "scalar int",