Skip to content

Commit

Permalink
Handle JSON.stringify(undefined)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
alexcrichton committed Sep 25, 2019
1 parent 55dbf94 commit 72f3468
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 1 deletion.
6 changes: 5 additions & 1 deletion crates/cli-support/src/js/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2626,7 +2626,11 @@ impl<'a> Context<'a> {

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

Intrinsic::AnyrefHeapLiveCount => {
Expand Down
1 change: 1 addition & 0 deletions tests/wasm/js_objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,5 @@ fn serde() {
assert_eq!(foo.d.a, 4);

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

0 comments on commit 72f3468

Please sign in to comment.