Skip to content

Commit

Permalink
Add flag for disabling HTML escaping
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
tidwall committed Jul 30, 2024
1 parent 28d458b commit 5ab551f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
14 changes: 14 additions & 0 deletions gjson.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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] == '"' {
Expand Down
2 changes: 1 addition & 1 deletion gjson_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down

0 comments on commit 5ab551f

Please sign in to comment.