Skip to content

Commit

Permalink
fix: escape json for string input (moonbitlang#858)
Browse files Browse the repository at this point in the history
  • Loading branch information
qazxcdswe123 authored Aug 15, 2024
1 parent 68d6319 commit 36d61f6
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 2 deletions.
36 changes: 35 additions & 1 deletion builtin/json.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,42 @@ pub fn Double::to_json(self : Double) -> Json {
Number(self)
}

fn escape_json_string(str : String) -> String {
fn to_hex_digit(i : Int) -> Char {
if i < 10 {
Char::from_int('0'.to_int() + i)
} else {
Char::from_int('a'.to_int() + (i - 10))
}
}

let buf = Buffer::new(size_hint=str.length())
for i = 0; i < str.length(); i = i + 1 {
let c = str[i]
match c {
'\n' => buf.write_string("\\n")
'\r' => buf.write_string("\\r")
'\b' => buf.write_string("\\b")
'\t' => buf.write_string("\\t")
_ => {
let code = c.to_int()
if code == 0x0C {
buf.write_string("\\f")
} else if code < 0x20 {
buf.write_string("\\u00")
buf.write_char(to_hex_digit(code / 16))
buf.write_char(to_hex_digit(code % 16))
} else {
buf.write_char(c)
}
}
}
}
buf.to_string()
}

pub fn String::to_json(self : String) -> Json {
String(self)
String(escape_json_string(self))
}

pub fn Char::to_json(self : Char) -> Json {
Expand Down
3 changes: 2 additions & 1 deletion json/json_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -295,11 +295,12 @@ test "stringify escape" {
"\n": "\n\r\t\x0C",
"\\": "/",
"\x1F": "\x01",
"actual": "\x00",
}
inspect!(
json.stringify(),
content=
#|{"\b":"\"hello\"","\n":"\n\r\t\f","\\":"\/","\u001f":"\u0001"}
#|{"\b":"\"hello\"","\n":"\n\r\t\f","\\":"\/","\u001f":"\u0001","actual":"\u0000"}
,
)
match @json.parse?(json.stringify()) {
Expand Down
24 changes: 24 additions & 0 deletions json/to_json_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,30 @@ test "String::to_json" {
#|String("a,\"b\",c")
,
)
inspect!(
"\"".to_json(),
content=
#|String("\"")
,
)
inspect!(
"\x00".to_json(),
content=
#|String("\\u0000")
,
)
inspect!(
"\n".to_json(),
content=
#|String("\\n")
,
)
inspect!(
"\\".to_json(),
content=
#|String("\\")
,
)
}

test "Char::to_json" {
Expand Down

0 comments on commit 36d61f6

Please sign in to comment.