json2: encode ascii chars < 0x20 in json (#12494)

pull/12503/head
Don Park 2021-11-17 21:34:00 -08:00 committed by GitHub
parent 26fbf1885d
commit ae54cd78f5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 17 additions and 0 deletions

View File

@ -5,6 +5,13 @@ fn test_raw_decode_string() ? {
assert str.str() == 'Hello!'
}
fn test_raw_decode_string_escape() ? {
jstr := raw_decode('"\u001b"') ?
str := jstr.str()
assert str.len == 1
assert str[0] == 27
}
fn test_raw_decode_number() ? {
num := raw_decode('123') ?
assert num.int() == 123

View File

@ -150,6 +150,9 @@ fn json_string(s string) string {
}
} else if chr == `"` || chr == `/` || chr == `\\` {
sb.write_string('\\' + chr.ascii_str())
} else if int(chr) < 0x20 {
hex_code := chr.hex()
sb.write_string('\\u00$hex_code')
} else {
sb.write_b(chr)
}

View File

@ -5,6 +5,13 @@ fn test_json_string_characters() {
assert text.json_str() == '\\n\\r\\b\\f\\t\\\\\\"\\/'
}
fn test_json_escape_low_chars() {
esc := '\u001b'
assert esc.len == 1
text := json2.Any(esc)
assert text.json_str() == r'\u001b'
}
fn test_json_string() {
text := json2.Any('test')
assert text.json_str() == r'te\u2714st'