evestera / json_typegen

Tools and libraries to create types for Rust, Kotlin, TypeScript and Python from JSON samples
https://typegen.vestera.as
Apache License 2.0
268 stars 26 forks source link

Improve field naming for mixed numbers and other characters #4

Closed evestera closed 3 years ago

evestera commented 7 years ago

Prompted by a reddit comment. The following JSON:

{ 
    "layouts": {
        "1900x200": "1",
        "1900*200": "2",
        "1900_200": "3"
    }
}

Results in renamed fields:

1900x200 -> n1900_x200
1900*200 -> n1900200
1900_200 -> n19002002

A suggested improvement:

1900x200 --> n1900x200
1900*200 --> n1900_200
1900_200 --> n1900_200_2
evestera commented 7 years ago

Also applies to type names. Currently this JSON:

{
    "layouts": {
        "1900x200": {},
        "1900*200": {},
        "1900_200": {}
    }
}

Results in type names:

struct N19002002 {}
struct N1900200 {}
struct N1900X200 {}
zackmdavis commented 3 years ago

Relatedly, the tool seems to be doing some renamings that aren't necessary? The JSON key class_5min generates the code

    #[serde(rename = "class_5min")]
    pub class5_min: String,

but pub class_5min: String works; it was already a valid struct field name.

evestera commented 3 years ago

Relatedly, the tool seems to be doing some renamings that aren't necessary? The JSON key class_5min generates the code


    #[serde(rename = "class_5min")]

    pub class5_min: String,

but pub class_5min: String works; it was already a valid struct field name.

Hmm, not able to reproduce it with { "class5_min": 3 } and default settings. Did you have a rename_all or some other setting perhaps?

zackmdavis commented 3 years ago

not able to reproduce it with { "class5_min": 3 }

The number is after the underscore in the original JSON, but the tool is putting it before the underscore in the Rust struct field and adding a Serde rename attribute. Reproduction:

zmd@ReflectiveCoherence:~/Code/Misc$ cat demo.json 
{ "class_5min": 3 }
zmd@ReflectiveCoherence:~/Code/Misc$ json_typegen demo.json -o demo.rs -n Demo
[/home/zmd/.cargo/registry/src/github.com-1ecc6299db9ec823/json_typegen_shared-0.6.0/src/unwrap.rs:5] pointer = ""
zmd@ReflectiveCoherence:~/Code/Misc$ cat demo.rs 
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
pub struct Demo {
    #[serde(rename = "class_5min")]
    pub class5_min: i64,
}
evestera commented 3 years ago

The number is after the underscore in the original JSON, but the tool is putting it before the underscore in the Rust struct field and adding a Serde rename attribute.

Thanks for the clarification. That is definitely some unwanted/silly behaviour, so thanks for a good test-case to add/fix. 🙂