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
This commit is contained in:
Alex Crichton 2019-09-23 08:08:34 -07:00
parent 55dbf9478f
commit 72f346871c
2 changed files with 6 additions and 1 deletions

View File

@ -2626,7 +2626,11 @@ impl<'a> Context<'a> {
Intrinsic::JsonSerialize => { Intrinsic::JsonSerialize => {
assert_eq!(args.len(), 1); 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 => { Intrinsic::AnyrefHeapLiveCount => {

View File

@ -144,4 +144,5 @@ fn serde() {
assert_eq!(foo.d.a, 4); assert_eq!(foo.d.a, 4);
assert_eq!(JsValue::from("bar").into_serde::<String>().unwrap(), "bar"); assert_eq!(JsValue::from("bar").into_serde::<String>().unwrap(), "bar");
assert_eq!(JsValue::undefined().into_serde::<i32>().ok(), None);
} }