Skip to content

Commit

Permalink
Disable html escaping
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
tidwall committed Jul 29, 2024
1 parent c2bc5a4 commit 28d458b
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
3 changes: 0 additions & 3 deletions gjson.go
Original file line number Diff line number Diff line change
Expand Up @@ -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] == '"' {
Expand Down
12 changes: 10 additions & 2 deletions gjson_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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()))
Expand Down

0 comments on commit 28d458b

Please sign in to comment.