Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
json: encode \b and \f like the Go 1.22 stdlib does
  • Loading branch information
extemporalgenome committed Jun 9, 2025
commit 953e0aab1bd450291a81cf180e8274c3dd7ab777
25 changes: 2 additions & 23 deletions json/encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,30 +158,9 @@ func (e encoder) encodeString(b []byte, p unsafe.Pointer) ([]byte, error) {
}

switch c {
case '\\', '"':
case '\\', '"', '\b', '\f', '\n', '\r', '\t':
b = append(b, s[i:j]...)
b = append(b, '\\', c)
i = j + 1
j = j + 1
continue

case '\n':
b = append(b, s[i:j]...)
b = append(b, '\\', 'n')
i = j + 1
j = j + 1
continue

case '\r':
b = append(b, s[i:j]...)
b = append(b, '\\', 'r')
i = j + 1
j = j + 1
continue

case '\t':
b = append(b, s[i:j]...)
b = append(b, '\\', 't')
b = append(b, '\\', escapeByteRepr(c))
i = j + 1
j = j + 1
continue
Expand Down
4 changes: 2 additions & 2 deletions json/golang_encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -685,11 +685,11 @@ var encodeStringTests = []struct {
{"\x05", `"\u0005"`},
{"\x06", `"\u0006"`},
{"\x07", `"\u0007"`},
{"\x08", `"\u0008"`},
{"\x08", `"\b"`},
{"\x09", `"\t"`},
{"\x0a", `"\n"`},
{"\x0b", `"\u000b"`},
{"\x0c", `"\u000c"`},
{"\x0c", `"\f"`},
{"\x0d", `"\r"`},
{"\x0e", `"\u000e"`},
{"\x0f", `"\u000f"`},
Expand Down
19 changes: 19 additions & 0 deletions json/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,25 @@ func escapeIndex(s string, escapeHTML bool) int {
return -1
}

func escapeByteRepr(b byte) byte {
switch b {
case '\\', '"':
return b
case '\b':
return 'b'
case '\f':
return 'f'
case '\n':
return 'n'
case '\r':
return 'r'
case '\t':
return 't'
}

return 0
}

// below return a mask that can be used to determine if any of the bytes
// in `n` are below `b`. If a byte's MSB is set in the mask then that byte was
// below `b`. The result is only valid if `b`, and each byte in `n`, is below
Expand Down