Skip to content

Commit ad271d5

Browse files
authored
feat: handle escape and null value (#419)
1 parent fe4fc1e commit ad271d5

File tree

2 files changed

+26
-12
lines changed

2 files changed

+26
-12
lines changed

jsonwriter/writer.go

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,15 @@ import (
1818
"bytes"
1919
"errors"
2020
"fmt"
21-
"strings"
21+
"strconv"
2222

2323
"gopkg.in/yaml.v3"
2424
)
2525

26-
const indentation = " "
27-
28-
// basic escaping, will need to be improved or replaced
29-
func escape(s string) string {
30-
s = strings.Replace(s, "\n", "\\n", -1)
31-
s = strings.Replace(s, "\"", "\\\"", -1)
32-
return s
33-
}
26+
const (
27+
indentation = " "
28+
null = "null"
29+
)
3430

3531
type writer struct {
3632
b bytes.Buffer
@@ -85,15 +81,15 @@ func (w *writer) writeScalar(node *yaml.Node, indent string) {
8581
}
8682
switch node.Tag {
8783
case "!!str":
88-
w.writeString("\"")
89-
w.writeString(escape(node.Value))
90-
w.writeString("\"")
84+
w.writeString(strconv.Quote(node.Value))
9185
case "!!int":
9286
w.writeString(node.Value)
9387
case "!!float":
9488
w.writeString(node.Value)
9589
case "!!bool":
9690
w.writeString(node.Value)
91+
case "!!null":
92+
w.writeString(null)
9793
}
9894
}
9995

jsonwriter/writer_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ func TestMarshal(t *testing.T) {
3737
scalarBoolTestCase(),
3838
scalarFloatTestCase(),
3939
scalarIntTestCase(),
40+
scalarStringTestCase(),
41+
scalarNullTestCase(),
4042
sequenceStringArrayTestCase(),
4143
sequenceBoolArrayTestCase(),
4244
sequenceFloatArrayTestCase(),
@@ -88,6 +90,22 @@ func scalarFloatTestCase() *MarshalTestCase {
8890
}
8991
}
9092

93+
func scalarStringTestCase() *MarshalTestCase {
94+
return &MarshalTestCase{
95+
Name: "scalar string",
96+
Node: compiler.NewScalarNodeForString("a\\b\nc\""),
97+
Expected: "\"a\\\\b\\nc\\\"\"\n",
98+
}
99+
}
100+
101+
func scalarNullTestCase() *MarshalTestCase {
102+
return &MarshalTestCase{
103+
Name: "scalar null",
104+
Node: compiler.NewNullNode(),
105+
Expected: "null\n",
106+
}
107+
}
108+
91109
func scalarIntTestCase() *MarshalTestCase {
92110
return &MarshalTestCase{
93111
Name: "scalar int",

0 commit comments

Comments
 (0)