Skip to content

Commit 72f3468

Browse files
committed
Handle JSON.stringify(undefined)
Turns out that `JSON.stringify(undefined)` doesn't actually return a string, it returns `undefined`! If we're requested to serialize `undefined` into JSON instead just interpret it as `null` which should have the expected semantics of serving as a placeholder for `None`. Closes #1778
1 parent 55dbf94 commit 72f3468

File tree

2 files changed

+6
-1
lines changed

2 files changed

+6
-1
lines changed

crates/cli-support/src/js/mod.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2626,7 +2626,11 @@ impl<'a> Context<'a> {
26262626

26272627
Intrinsic::JsonSerialize => {
26282628
assert_eq!(args.len(), 1);
2629-
format!("JSON.stringify({})", args[0])
2629+
// Turns out `JSON.stringify(undefined) === undefined`, so if
2630+
// we're passed `undefined` reinterpret it as `null` for JSON
2631+
// purposes.
2632+
prelude.push_str(&format!("const obj = {};\n", args[0]));
2633+
"JSON.stringify(obj === undefined ? null : obj)".to_string()
26302634
}
26312635

26322636
Intrinsic::AnyrefHeapLiveCount => {

tests/wasm/js_objects.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,4 +144,5 @@ fn serde() {
144144
assert_eq!(foo.d.a, 4);
145145

146146
assert_eq!(JsValue::from("bar").into_serde::<String>().unwrap(), "bar");
147+
assert_eq!(JsValue::undefined().into_serde::<i32>().ok(), None);
147148
}

0 commit comments

Comments
 (0)