callum-oakley / json5-rs

A Rust JSON5 serializer and deserializer which speaks Serde.
ISC License
184 stars 23 forks source link

reading a numeric key in objects returns `expected identifier or string` error #25

Open AldoMX opened 4 years ago

AldoMX commented 4 years ago

Hi, thank you for writing the JSON5 serializer/deserializer. During my tests I found that an object like { 0: "hello" } returns error, I leave you a test case here:

#[test]
fn json5test() {
    #[derive(Serialize, Deserialize, PartialEq, Debug)]
    struct Duck {
        name: String,
        age: usize,
    }

    #[derive(Serialize, Deserialize, PartialEq, Debug)]
    struct DuckFamily {
        triplets: BTreeMap<usize, Duck>,
    }

    let family = {
        let mut triplets = BTreeMap::new();
        triplets.insert(
            1,
            Duck {
                name: "Huey".to_owned(),
                age: 9,
            },
        );
        triplets.insert(
            2,
            Duck {
                name: "Dewey".to_owned(),
                age: 9,
            },
        );
        triplets.insert(
            3,
            Duck {
                name: "Louie".to_owned(),
                age: 9,
            },
        );
        DuckFamily { triplets }
    };

    let encoded = json5::to_string(&family).unwrap();
    println!("{:?}", &encoded);
    let decoded: DuckFamily = json5::from_str(&encoded).unwrap();  // error here
    println!("{:?}", &decoded);
    assert_eq!(decoded, family);
}
AldoMX commented 4 years ago

Researching more about JSON5 I found out that numeric keys (ie. { 0: "hello" }) are not valid, but string keys (ie. { "0": "hello" }) are.

Then there are 2 different issues with the test I provided:

  1. Number keys are being serialized without quotes
  2. String keys are not being parsed as numbers when the target type expects a number