json icon indicating copy to clipboard operation
json copied to clipboard

Error message points to wrong line when using attribute flatten

Open dgel opened this issue 4 years ago • 2 comments

(I'm not sure if this belongs here or in serde, but I think it's to do with parsing json, so I put it here)

When parsing a struct containing a map annotated with flatten, error messages pertaining to missing data in the values of the map point to the line closing the containing object. See example below:

use std::collections::BTreeMap;

#[derive(Deserialize, Debug)]
struct Values {
    #[serde(flatten)]
    index: BTreeMap<String, Value>,
}

#[derive(Deserialize, Debug)]
struct Value {
    id: u32,
}

fn main() {
    let input = r#"{
  "a": { "id": 0 },
  "b": { "missing": 1 },
  "c": { "id": 2 },
  "d": { "id": 3 },
  "e": { "id": 4 },
  "f": { "id": 5 },
  "g": { "id": 6 }
} 
"#;

    // Expected: issues an error at the end of line 3
    let values = serde_json::from_str(input);
    match values {
        Ok(sets) => {
            let sets: BTreeMap<String, Value> = sets;
            println!("Ok: {:?}", sets);
        }
        Err(error) => println!("Error reading the json file: {}", error),
    }

    // Surprising: issues an error on line 9
    let values = serde_json::from_str(input);
    match values {
        Ok(sets) => {
            let sets: Values = sets;
            println!("Ok: {:?}", sets);
        }
        Err(error) => println!("Error reading the json file: {}", error),
    }
}

dgel avatar Feb 15 '20 21:02 dgel

same issue here :/

firstdorsal avatar Feb 14 '22 22:02 firstdorsal

I don't think this is specific to serde_json. I can reproduce it e.g. with serde_yaml as well.

This issue has already been filed in the serde repo: https://github.com/serde-rs/serde/issues/2035

mvforell avatar Feb 16 '22 14:02 mvforell