JSON to Rust Converter
Convert JSON to Rust Online
Use our free json to rust converter to generate properly annotated Rust struct definitions with json to serde derive macros from any JSON data instantly. Whether you are building typed data models for Actix Web handlers, creating configuration structs for CLI applications, or scaffolding API response types for Rust microservices, this tool produces clean, compilable Rust code from your JSON input.
What is JSON Format
JSON, short for JavaScript Object Notation, is a lightweight data interchange format that serves as the universal standard for web-based data communication. Its syntax of key-value pairs enclosed in curly braces and ordered arrays enclosed in square brackets makes it intuitive for both humans and machines. JSON supports strings, numbers, booleans, null, nested objects, and arrays as value types.
JSON has become the default format for REST API responses, NoSQL database storage, configuration files, and data exchange between microservices. The Rust ecosystem provides excellent JSON support through the serde and serde_json crates, which handle serialization and deserialization between JSON strings and Rust structs using derive macros. This combination has become the standard approach for JSON handling in virtually every Rust web framework and application.
What is Rust Struct Format
Rust structs are custom data types that group together related fields under a single name, serving as the primary mechanism for defining structured data in the Rust programming language. Rust structs are value types by default, stored on the stack for small sizes, and support pattern matching, destructuring, and implementation blocks for associated methods. Combined with Rust ownership and borrowing system, structs provide memory-safe data modeling without garbage collection overhead.
The serde framework is the de facto standard for serialization in Rust, providing derive macros that automatically generate serialization and deserialization code for structs. Adding #[derive(Serialize, Deserialize)] to a struct enables automatic JSON conversion through serde_json. Serde supports field renaming with the rename attribute, default values, skipping fields, flattening nested structures, and custom serialization logic. Rust types used in struct fields include String, i32, i64, f64, bool, Vec for arrays, Option for nullable values, and HashMap for dynamic key-value pairs. Rust structs are widely used in web servers built with Actix Web, Axum, and Rocket, as well as CLI tools, embedded systems, and WebAssembly applications.
How the Conversion Works
Converting JSON to Rust structs involves analyzing the structure and values of a JSON document to infer appropriate Rust types for each field. The converter parses the input JSON, examines each value to determine its Rust type, and generates struct definitions annotated with serde derive macros. Strings become String, integers become i64, floating-point numbers become f64, booleans become bool, null values become Option types, arrays become Vec collections, and nested objects become separate named structs.
The conversion engine follows Rust naming conventions by converting JSON keys to snake_case field names and PascalCase struct names. When the original JSON key differs from the Rust field name, a serde rename attribute is added automatically. If your data originates in another format, you can first convert TOML to JSON before generating Rust structs, which is especially useful for Cargo.toml workflows. For working with your JSON data in other ways, try our JSON to Go struct converter for another systems language, or explore the JSON to YAML converter for configuration file generation. You can also convert JSON to TOML for Rust project configuration files.
Syntax Comparison
The mapping between JSON data and Rust structs is direct and well-defined. A JSON object like this:
// JSON
{
"userName": "Alice",
"age": 30,
"active": true,
"score": 95.5
}
Generates the following Rust struct:
// Rust
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct Root {
#[serde(rename = "userName")]
pub user_name: String,
pub age: i64,
pub active: bool,
pub score: f64,
}
JSON arrays are mapped to Rust Vec types with appropriate element types. A JSON array of strings becomes Vec<String>, while an array of objects generates a separate struct and uses Vec<ChildStruct> as the field type. Nested JSON objects produce additional named structs referenced as field types in the parent struct. The serde rename attribute preserves the original JSON key name when it differs from the snake_case Rust field name.
Common Use Cases
The most common use case for JSON to Rust struct conversion is creating request and response models for web API handlers. Rust developers building services with Actix Web, Axum, or Rocket need struct definitions that match the JSON payloads they receive and send. Rather than manually writing structs by inspecting API documentation, developers can paste a sample JSON payload and instantly generate the required struct hierarchy with proper serde annotations.
Another frequent scenario involves consuming external APIs from Rust applications. When integrating with third-party services that return JSON responses, developers need Rust structs for deserialization with serde_json. Configuration file parsing is another common use case, where JSON configuration files need corresponding Rust structs for loading settings at application startup. CLI tool development in Rust also benefits from this conversion when processing JSON input from files or standard input streams.
JSON to Rust Examples
The following examples demonstrate how various JSON structures are converted into Rust struct definitions with serde annotations. These cover the most common patterns encountered when generating typed models from API responses and configuration data.
A JSON object with nested structures generates multiple related structs:
// JSON Input
{
"config": {
"appName": "my-service",
"port": 8080,
"debug": false,
"database": {
"host": "localhost",
"port": 5432,
"poolSize": 10
},
"allowedOrigins": ["https://example.com"]
}
}
// Rust Output
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct Database {
pub host: String,
pub port: i64,
#[serde(rename = "poolSize")]
pub pool_size: i64,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
#[serde(rename = "appName")]
pub app_name: String,
pub port: i64,
pub debug: bool,
pub database: Database,
#[serde(rename = "allowedOrigins")]
pub allowed_origins: Vec<String>,
}
A JSON array with nullable fields demonstrates Option type handling:
// JSON Input
{
"users": [
{"id": 1, "name": "Alice", "bio": null},
{"id": 2, "name": "Bob", "bio": "Rustacean"}
]
}
// Rust Output
#[derive(Debug, Serialize, Deserialize)]
pub struct User {
pub id: i64,
pub name: String,
pub bio: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Root {
pub users: Vec<User>,
}
Frequently Asked Questions
Does the converter include serde derive macros?
Yes, every generated struct includes the #[derive(Debug, Serialize, Deserialize)] attribute and the necessary use serde::{Deserialize, Serialize}; import statement. These derive macros enable automatic JSON serialization and deserialization through the serde_json crate. You will need to add serde and serde_json as dependencies in your Cargo.toml file with the derive feature enabled for serde.
How are JSON null values handled in Rust?
JSON null values are represented using Rust Option types. A field that can be either a string or null becomes Option<String> in the generated struct. When the JSON value is null, the Option will be None after deserialization. When the value is present, it will be Some containing the actual value. Serde handles Option fields automatically, making this the idiomatic Rust approach for nullable JSON fields.
How are JSON key names converted to Rust field names?
The converter transforms JSON key names to follow Rust naming conventions. CamelCase keys like firstName are converted to snake_case as first_name, and a #[serde(rename = "firstName")] attribute is added to maintain correct JSON mapping. Keys that are already in snake_case do not need a rename attribute. This ensures the generated code follows Rust community conventions while preserving compatibility with the original JSON structure.
Can I use the generated structs with Actix Web or Axum?
Yes, the generated Rust structs work seamlessly with all major Rust web frameworks. In Actix Web, you can use them with web::Json extractor for request bodies and Json wrapper for responses. In Axum, they work with the Json extractor and response types. The serde derive macros ensure compatibility with any framework that uses serde_json for JSON handling.
How are nested JSON objects handled?
Each nested JSON object generates a separate named Rust struct with its own fields and serde annotations. The parent struct references the child struct as a field type. Struct names are derived from the JSON key names using PascalCase convention. This modular approach produces clean, reusable code that follows Rust best practices for type organization.
What Rust numeric types are used for JSON numbers?
JSON integers are mapped to Rust i64 by default, providing a wide range that covers most use cases. JSON floating-point numbers are mapped to f64. If you need more specific types like i32, u64, or f32, you can modify the generated field types after conversion. Serde handles numeric type conversion automatically during deserialization, returning an error if the JSON value does not fit the target type.
Is the conversion performed securely?
Yes, the entire JSON to Rust conversion runs client-side in your browser. No data is transmitted to any external server, ensuring complete privacy and security. This makes the tool safe for converting JSON containing sensitive information such as API credentials, configuration secrets, or proprietary data structures. Your input never leaves your browser session.
How does this compare to generating Go or C# types?
Rust structs with serde are similar to Go structs with json tags in concept, but Rust offers stronger type safety through its ownership system and Option types for nullability. C# classes provide richer object-oriented features but lack Rust memory safety guarantees. Each target serves its ecosystem best. For alternatives, explore our JSON to Go struct converter or JSON to C# class generator.
FAQ
How does JSON to Rust Converter work?
Generate Rust structs from JSON.