From 90edebbcb6e192eaf8d588d20fb5656df65d29cd Mon Sep 17 00:00:00 2001 From: Alexei Yuzhakov Date: Mon, 27 Nov 2023 18:20:37 +0200 Subject: [PATCH] Fix #63: Correct quotes escaping for JSON strings --- internal/utils/utils.go | 8 +++++--- internal/utils/utils_test.go | 1 + test/data/json/formatted3.json | 3 +++ test/data/json/unformatted3.json | 1 + 4 files changed, 10 insertions(+), 3 deletions(-) create mode 100644 test/data/json/formatted3.json create mode 100644 test/data/json/unformatted3.json diff --git a/internal/utils/utils.go b/internal/utils/utils.go index ba730ab..92147a1 100644 --- a/internal/utils/utils.go +++ b/internal/utils/utils.go @@ -16,6 +16,7 @@ import ( "os/exec" "reflect" "regexp" + "strconv" "strings" ) @@ -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: diff --git a/internal/utils/utils_test.go b/internal/utils/utils_test.go index 5280a01..27ac602 100644 --- a/internal/utils/utils_test.go +++ b/internal/utils/utils_test.go @@ -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 { diff --git a/test/data/json/formatted3.json b/test/data/json/formatted3.json new file mode 100644 index 0000000..c1cf486 --- /dev/null +++ b/test/data/json/formatted3.json @@ -0,0 +1,3 @@ +{ + "key": "string \"with\" quotes" +} diff --git a/test/data/json/unformatted3.json b/test/data/json/unformatted3.json new file mode 100644 index 0000000..623b6b5 --- /dev/null +++ b/test/data/json/unformatted3.json @@ -0,0 +1 @@ +{ "key": "string \"with\" quotes" }