Generate const struct from json file

I have a .json file with somewhat static data that I would like to use in both my front- and backend.

Of course I could parse and load the file dynamically in the backend on startup, but I would much rather generate a const struct in a build script based on that file instead, which would catch any errors in said file while building instead of at runtime.

But I am a little lost when it comes to generating rust code in a build script.

For example this .json file:

{"a":1,"b":"test"}

Resulting in something like this:

struct JSONFileStruct {
    a: i32,
    b: &'static str
}

const JSONFILE: JSONFileStruct = JSONFileStruct { a: 1, b: "test" };

If you can make your parsing function a const fn then you can use include_str in std - Rust
to load the file. Then you would create a const or a static with that data. You wouldn't need a build script.

static CONFIG: MyConfig = MyConfig::parse(include_str!("path/to/my_config.json"))
1 Like

These libraries can help implement this process:

2 Likes