Skip to content

Commit 9b23287

Browse files
committed
Don't fail if an object is keyed with a string and we're expecting a number
1 parent e95552c commit 9b23287

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

src/libserialize/json.rs

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1951,7 +1951,10 @@ macro_rules! read_primitive {
19511951
String(s) => {
19521952
// re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
19531953
// is going to have a string here, as per JSON spec.
1954-
Ok(std::from_str::from_str(s.as_slice()).unwrap())
1954+
match std::from_str::from_str(s.as_slice()) {
1955+
Some(f) => Ok(f),
1956+
None => Err(ExpectedError("Number".to_string(), s)),
1957+
}
19551958
},
19561959
value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
19571960
}
@@ -1987,7 +1990,10 @@ impl ::Decoder<DecoderError> for Decoder {
19871990
String(s) => {
19881991
// re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
19891992
// is going to have a string here, as per JSON spec.
1990-
Ok(std::from_str::from_str(s.as_slice()).unwrap())
1993+
match std::from_str::from_str(s.as_slice()) {
1994+
Some(f) => Ok(f),
1995+
None => Err(ExpectedError("Number".to_string(), s)),
1996+
}
19911997
},
19921998
Null => Ok(f64::NAN),
19931999
value => Err(ExpectedError("Number".to_string(), format!("{}", value)))
@@ -3169,6 +3175,7 @@ mod tests {
31693175
_ => {} // it parsed and we are good to go
31703176
}
31713177
}
3178+
31723179
#[test]
31733180
fn test_prettyencode_hashmap_with_numeric_key() {
31743181
use std::str::from_utf8;
@@ -3189,6 +3196,7 @@ mod tests {
31893196
_ => {} // it parsed and we are good to go
31903197
}
31913198
}
3199+
31923200
#[test]
31933201
fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
31943202
use std::collections::HashMap;
@@ -3202,6 +3210,20 @@ mod tests {
32023210
let _hm: HashMap<uint, bool> = Decodable::decode(&mut decoder).unwrap();
32033211
}
32043212

3213+
#[test]
3214+
fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
3215+
use std::collections::HashMap;
3216+
use Decodable;
3217+
let json_str = "{\"a\":true}";
3218+
let json_obj = match from_str(json_str) {
3219+
Err(_) => fail!("Unable to parse json_str: {}", json_str),
3220+
Ok(o) => o
3221+
};
3222+
let mut decoder = Decoder::new(json_obj);
3223+
let result: Result<HashMap<uint, bool>, DecoderError> = Decodable::decode(&mut decoder);
3224+
assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
3225+
}
3226+
32053227
fn assert_stream_equal(src: &str,
32063228
expected: Vec<(JsonEvent, Vec<StackElement>)>) {
32073229
let mut parser = Parser::new(src.chars());

0 commit comments

Comments
 (0)