From 28d458b14c40df6321bba23bcb39579d468f5e97 Mon Sep 17 00:00:00 2001 From: tidwall Date: Mon, 29 Jul 2024 07:08:06 -0700 Subject: [PATCH] Disable html escaping This commit removes the automatic escaping of html characters, effectively rendering JSON strings in the same way as is the builtin Go encoder with SetEscapeHTML(false). This should not affect the quality of the resulting JSON and hopefully will not cause any downstream issues. --- gjson.go | 3 --- gjson_test.go | 12 ++++++++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/gjson.go b/gjson.go index eb8c707..3f9dcbe 100644 --- a/gjson.go +++ b/gjson.go @@ -1940,9 +1940,6 @@ func AppendJSONString(dst []byte, s string) []byte { dst = append(dst, 'u') dst = appendHex16(dst, uint16(s[i])) } - } else if s[i] == '>' || s[i] == '<' || s[i] == '&' { - dst = append(dst, '\\', 'u') - dst = appendHex16(dst, uint16(s[i])) } else if s[i] == '\\' { dst = append(dst, '\\', '\\') } else if s[i] == '"' { diff --git a/gjson_test.go b/gjson_test.go index 61c21f9..e26979a 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -2549,9 +2549,17 @@ func TestGroup(t *testing.T) { assert(t, res == `["123"]`) } +func goJSONMarshal(i interface{}) ([]byte, error) { + buffer := &bytes.Buffer{} + encoder := json.NewEncoder(buffer) + encoder.SetEscapeHTML(false) + err := encoder.Encode(i) + return bytes.TrimRight(buffer.Bytes(), "\n"), err +} + func testJSONString(t *testing.T, str string) { gjsonString := string(AppendJSONString(nil, str)) - data, err := json.Marshal(str) + data, err := goJSONMarshal(str) if err != nil { panic(123) } @@ -2579,7 +2587,7 @@ func TestJSONString(t *testing.T) { testJSONString(t, "R\xfd\xfc\a!\x82eO\x16?_\x0f\x9ab\x1dr") testJSONString(t, "_\xb9\v\xad\xb3|X!\xb6\xd9U&\xa4\x1a\x95\x04") data, _ := json.Marshal("\b\f") - if (string(data) == "\"\\b\\f\"") { + if string(data) == "\"\\b\\f\"" { // Go version 1.22+ encodes "\b" and "\f" correctly. testJSONString(t, "\b\f") rng := rand.New(rand.NewSource(time.Now().UnixNano()))