Skip to content

Commit

Permalink
Fix #63: Correct quotes escaping for JSON strings
Browse files Browse the repository at this point in the history
  • Loading branch information
sibprogrammer committed Nov 27, 2023
1 parent 8bd31ab commit 90edebb
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 3 deletions.
8 changes: 5 additions & 3 deletions internal/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"os/exec"
"reflect"
"regexp"
"strconv"
"strings"
)

Expand Down Expand Up @@ -431,11 +432,12 @@ func FormatJson(reader io.Reader, writer io.Writer, indent string, colors int) e
_, _ = fmt.Fprint(writer, newline, strings.Repeat(indent, level), tagColor("]"))
}
case string:
value := valueColor(token)
escapedToken := strconv.Quote(token.(string))
value := valueColor(escapedToken)
if tokenState == jsonTokenObjectColon {
value = attrColor(token)
value = attrColor(escapedToken)
}
_, _ = fmt.Fprintf(writer, "%s\"%s\"", prefix, value)
_, _ = fmt.Fprintf(writer, "%s%s", prefix, value)
case float64:
_, _ = fmt.Fprintf(writer, "%s%v", prefix, valueColor(token))
case json.Number:
Expand Down
1 change: 1 addition & 0 deletions internal/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ func TestFormatJson(t *testing.T) {
files := map[string]string{
"unformatted.json": "formatted.json",
"unformatted2.json": "formatted2.json",
"unformatted3.json": "formatted3.json",
}

for unformattedFile, expectedFile := range files {
Expand Down
3 changes: 3 additions & 0 deletions test/data/json/formatted3.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"key": "string \"with\" quotes"
}
1 change: 1 addition & 0 deletions test/data/json/unformatted3.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{ "key": "string \"with\" quotes" }

0 comments on commit 90edebb

Please sign in to comment.