Skip to content

Commit

Permalink
feat: handle escape and null value (#419)
Browse files Browse the repository at this point in the history
  • Loading branch information
Just-maple authored Feb 29, 2024
1 parent fe4fc1e commit ad271d5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 12 deletions.
20 changes: 8 additions & 12 deletions jsonwriter/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
}

Expand Down
18 changes: 18 additions & 0 deletions jsonwriter/writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ func TestMarshal(t *testing.T) {
scalarBoolTestCase(),
scalarFloatTestCase(),
scalarIntTestCase(),
scalarStringTestCase(),
scalarNullTestCase(),
sequenceStringArrayTestCase(),
sequenceBoolArrayTestCase(),
sequenceFloatArrayTestCase(),
Expand Down Expand Up @@ -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",
Expand Down

0 comments on commit ad271d5

Please sign in to comment.