# i18n-rs
`i18n-rs` is a lightweight internationalization helper designed to be embedded in any Rust web framework. It focuses on a familiar JSON-based translation file so you can reuse the dictionaries you already maintain while keeping your web stack framework agnostic.
## Features
- Loads translations from JSON files, strings, or any reader.
- Automatically flattens nested translation keys using dot notation.
- Optional fallback language for missing translations.
- Straightforward API that suits synchronous and async contexts alike.
## Installation
Add the crate to your project:
```toml
[dependencies]
i18n-rs = "1.0.0"
```
## Translator File Format
The crate expects a JSON object whose top-level keys are language identifiers. Each language contains nested objects and/or string values. Nested keys are automatically flattened using dot notation.
```json
{
"en": {
"greeting": {
"welcome": "Welcome",
"farewell": "Goodbye"
}
},
"fr": {
"greeting": {
"welcome": "Bienvenue"
}
}
}
```
The example above yields the keys `greeting.welcome` and `greeting.farewell`.
## Usage
```rust
use i18n_rs::Translator;
static JSON: &str = r#"{
"en": {
"welcome": "Welcome!",
"farewell": "See you later!",
"button": {
"submit": "Submit"
}
},
"es": {
"welcome": "¡Bienvenido!",
"button": {
"submit": "Enviar"
}
}
}"#;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let translator = Translator::builder()
.fallback_language("en")
.load_from_str(JSON)?;
assert_eq!(
translator.translate("es", "button.submit"),
Some("Enviar")
);
// Missing keys gracefully use the fallback language.
assert_eq!(
translator.translate_with_fallback("es", "farewell"),
Some("See you later!")
);
Ok(())
}
```