json icon indicating copy to clipboard operation
json copied to clipboard

Better error message for deserializing into array with more elements than expected

Open repnop opened this issue 5 years ago • 1 comments

serde_json reports the error Error("trailing characters", line: ..., column: ...) whenever there are more elements in the JSON array than in the struct definition, which is very confusing as the JSON is valid.

Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7aea3d19b21cea1292a7e8d9d8fae1d3

Perhaps it could detect if there are more elements and error with something like Error("more elements than array would contain", line: ..., column: ...)?

repnop avatar May 10 '19 14:05 repnop

I came here with the same problem. I even made a playground link as well: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=76db96837382e6f774f88c3110cc2201

I'd definitely be interested in writing a PR to fix this, although a couple tips about where to look would be greatly appreciated.

I suppose this would be the test case that we'd like to have pass:

    let more_elements_err: [f32; 2] = serde_json::from_str("[1.0, 2.3, 3.0]").unwrap_err();
    assert_eq!(more_elements_err.to_string(), "more elements than array should contain");

Alternatively, perhaps we should consider that we have a precedent to follow. Unknown map fields are simply ignored. If you think of arrays as maps with implied numerical keys, then it would make since for us to simply ignore the extra digits, so perhaps the test case should be:

    let two_list: [f32; 2] = serde_json::from_str("[1.0, 2.3, 3.0]")
        .expect("couldn't parse list with three elements into a list with two");
    assert_eq!(two_list, [1.0, 2.3]);

cedric-h avatar Nov 27 '19 23:11 cedric-h