Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: jsonwriter handle escape and null value #419

Merged
merged 3 commits into from Feb 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 8 additions & 12 deletions jsonwriter/writer.go
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
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