Skip to content

Commit 8188aa4

Browse files
committed
Fixed some two-character escapes like \n not escaping right
1 parent 4d44309 commit 8188aa4

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

escape.go

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,18 @@ func decodeUnicodeEscape(in []byte) (rune, int) {
6969

7070
}
7171

72+
// backslashCharEscapeTable: when '\X' is found for some byte X, it is to be replaced with backslashCharEscapeTable[X]
73+
var backslashCharEscapeTable = [...]byte{
74+
'"': '"',
75+
'\\': '\\',
76+
'/': '/',
77+
'b': '\b',
78+
'f': '\f',
79+
'n': '\n',
80+
'r': '\r',
81+
't': '\t',
82+
}
83+
7284
// unescapeToUTF8 unescapes the single escape sequence starting at 'in' into 'out' and returns
7385
// how many characters were consumed from 'in' and emitted into 'out'.
7486
// If a valid escape sequence does not appear as a prefix of 'in', (-1, -1) to signal the error.
@@ -80,9 +92,9 @@ func unescapeToUTF8(in, out []byte) (inLen int, outLen int) {
8092

8193
// https://tools.ietf.org/html/rfc7159#section-7
8294
switch e := in[1]; e {
83-
case '"', '\\', 'n', 't', 'r', '/', 'b', 'f':
84-
// Valid basic 2-character escapes
85-
out[0] = e
95+
case '"', '\\', '/', 'b', 'f', 'n', 'r', 't':
96+
// Valid basic 2-character escapes (use lookup table)
97+
out[0] = backslashCharEscapeTable[e]
8698
return 2, 1
8799
case 'u':
88100
// Unicode escape

parser_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,13 @@ var getTests = []GetTest{
167167
isFound: true,
168168
data: `1`,
169169
},
170+
GetTest{
171+
desc: `key and value with whitespace escapes`,
172+
json: `{"key\b\f\n\r\tkey":"value\b\f\n\r\tvalue"}`,
173+
path: []string{"key\b\f\n\r\tkey"},
174+
isFound: true,
175+
data: `value\b\f\n\r\tvalue`, // value is not unescaped since this is Get(), but the key should work correctly
176+
},
170177
GetTest{
171178
desc: `key with Unicode escape`,
172179
json: `{"a\u00B0b":1}`,
@@ -371,6 +378,13 @@ var getStringTests = []GetTest{
371378
isFound: true,
372379
data: `\"`,
373380
},
381+
GetTest{
382+
desc: `key and value with whitespace escapes`,
383+
json: `{"key\b\f\n\r\tkey":"value\b\f\n\r\tvalue"}`,
384+
path: []string{"key\b\f\n\r\tkey"},
385+
isFound: true,
386+
data: "value\b\f\n\r\tvalue", // value is unescaped since this is GetString()
387+
},
374388
}
375389

376390
var getBoolTests = []GetTest{

0 commit comments

Comments
 (0)