From 5ab551f3ac05551c469e5f5ab26154a49f69afcf Mon Sep 17 00:00:00 2001 From: tidwall Date: Tue, 30 Jul 2024 04:47:27 -0700 Subject: [PATCH] Add flag for disabling HTML escaping Adds the DisableEscapeHTML flag for disable the automatic escaping of the HTML characters '>', '<' and '&'. The previous commit introduced a potentially breaking change by removing HTML escaping altogether. This commit fixes that issue by allowing the user to choose at runtime. --- gjson.go | 14 ++++++++++++++ gjson_test.go | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/gjson.go b/gjson.go index 3f9dcbe..779fe61 100644 --- a/gjson.go +++ b/gjson.go @@ -1917,6 +1917,16 @@ func appendHex16(dst []byte, x uint16) []byte { ) } +// DisableEscapeHTML will disable the automatic escaping of certain +// "problamatic" HTML characters when encoding to JSON. +// These character include '>', '<' and '&', which get escaped to \u003e, +// \u0026, and \u003c respectively. +// +// This is a global flag and will affect all further gjson operations. +// Ideally, if used, it should be set one time before other gjson functions +// are called. +var DisableEscapeHTML = false + // AppendJSONString is a convenience function that converts the provided string // to a valid JSON string and appends it to dst. func AppendJSONString(dst []byte, s string) []byte { @@ -1940,6 +1950,10 @@ func AppendJSONString(dst []byte, s string) []byte { dst = append(dst, 'u') dst = appendHex16(dst, uint16(s[i])) } + } else if !DisableEscapeHTML && + (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 e26979a..079e1cf 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -2552,7 +2552,7 @@ func TestGroup(t *testing.T) { func goJSONMarshal(i interface{}) ([]byte, error) { buffer := &bytes.Buffer{} encoder := json.NewEncoder(buffer) - encoder.SetEscapeHTML(false) + encoder.SetEscapeHTML(!DisableEscapeHTML) err := encoder.Encode(i) return bytes.TrimRight(buffer.Bytes(), "\n"), err }