Home › Developer Tools › JSON to Rust Struct

JSON to Rust Struct

Paste a JSON object or API response and get idiomatic Rust structs that compile with serde: snake_case fields, #[serde(rename_all)] or per-field renames, Option<T> for nullable values, Vec<T> for arrays and a struct for every nested object. Everything runs in your browser.

Last updated:

Your JSON is parsed locally in this tab and never uploaded. Tip: Ctrl + Enter generates.

Advertisement
Advertisement

How to use the JSON to Rust Struct

  1. Paste your JSON into the left box or open a .json file. A sample is loaded so you can see the output right away.
  2. Name the root struct, for example User or ApiResponse.
  3. Pick the options: which serde derives to add, the integer type, rename_all or per-field renames, Option for missing fields and extra derives.
  4. Press Generate Rust Structs. With Live update on, the code refreshes as you type.
  5. Copy or download the .rs file, add serde (with the derive feature) and serde_json to Cargo.toml, and call serde_json::from_str.

Example: JSON to Rust structs with serde

This response has camelCase keys, a nullable value, a Rust keyword as a key and an array of objects where one key is optional:

{ "userId": 42, "displayName": "Ada", "avatarUrl": null,
  "posts": [ { "id": 1, "type": "article", "score": 4.5 },
             { "id": 2, "type": "note", "score": 3, "coverImage": "a.png" } ] }

With the default options the generator produces:

use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Root {
    pub user_id: i64,
    pub display_name: String,
    pub avatar_url: Value,
    pub posts: Vec<Post>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Post {
    pub id: i64,
    pub r#type: String,
    pub score: f64,
    pub cover_image: Option<String>,
}

score is f64 because one item has 4.5, cover_image is an Option because only one post has it, and avatar_url is Value because it is only ever null, so its type is unknown. Change it to Option<String> once you know.

How JSON values map to Rust types

JSON valueRust type
"text"String
42i64 (or i32 / u64 by option)
3.14, 1e6f64
true / falsebool
"x" or nullOption<String>
Key missing in some itemsOption<T> (or #[serde(default)])
{ … }A named struct
{}HashMap<String, Value>
[1, 2] / []Vec<i64> / Vec<Value>
null only, or mixed typesserde_json::Value

Using the structs

# Cargo.toml
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"

// main.rs
let root: Root = serde_json::from_str(&json)?;
println!("{}", root.posts[0].r#type);
let back = serde_json::to_string_pretty(&root)?;
  • Unknown keys are ignored by default. Turn on deny_unknown_fields to make deserialization fail when the JSON has keys the struct does not know.
  • skip_serializing_if leaves None fields out of the output instead of writing null, which keeps serialized JSON closer to the original.
  • Dates stay String. For typed timestamps add the chrono crate with its serde feature and change the field to chrono::DateTime<chrono::Utc>.

Frequently asked questions

Which crates do the generated structs need?

Add serde with the derive feature and serde_json to Cargo.toml: serde = { version = "1", features = ["derive"] } and serde_json = "1". The structs use #[derive(Serialize, Deserialize)] from serde and, when a field can hold mixed types, serde_json::Value.

How are JSON keys turned into Rust field names?

Each key is split into words at camelCase boundaries, dashes, spaces and underscores, then joined in snake_case, so userName becomes user_name. If most keys in a struct follow one convention, the generator adds #[serde(rename_all = "camelCase")] (or PascalCase, kebab-case or SCREAMING_SNAKE_CASE) and only adds #[serde(rename = "...")] to keys that do not fit, so serde still reads the original JSON.

When does a field become Option<T>?

A field becomes Option<T> when it is null in at least one place, or (with the option on) when the key is missing from some items of an array. serde deserializes a missing Option field as None automatically. If you turn the option off, missing fields get #[serde(default)] instead.

What happens to Rust keywords like type or match?

Keywords are written as raw identifiers, for example pub r#type: String. serde strips the r# prefix, so the field still maps to the JSON key "type". self, Self, super and crate cannot be raw identifiers, so they get a trailing underscore plus a rename attribute.

How are numbers typed?

Whole numbers become i64 by default, and numbers with a decimal point or exponent become f64. You can choose i32 when every value fits in 32 bits, or u64 when no value is negative. If a field mixes whole and decimal numbers it becomes f64. Integers too large for 64 bits are treated as f64.

What about null-only fields, empty arrays and mixed types?

If a value is always null, its real type cannot be known, so it becomes serde_json::Value. Empty arrays become Vec<Value> and fields that mix types (such as a string in one item and a number in another) also use Value, because Rust has no ad-hoc union types. Replace them with a concrete type or an enum once you know the data.

Is my JSON uploaded anywhere?

No. Parsing and code generation are plain JavaScript running in this page, so API responses containing personal or secret data never leave your device.

Are all the tools on FreeToolCabin tested for quality and accuracy?

Yes! Every tool on our site undergoes automated Q/A testing in real browser environments to ensure high precision, correct output, and zero errors. If you happen to spot a bug or have a suggestion, please contact us at [email protected] and our team will review it right away.

Related tools

JSON to Go StructTurn JSON into Go structs with inferred types, nested structs and json tags.JSON to TypeScriptGenerate TypeScript interfaces or types from JSON, with nested types and optional fields.JSON to Python ClassGenerate Python dataclasses, Pydantic models or TypedDicts with type hints from JSON.JSON FormatterBeautify, minify and validate JSON, with a collapsible tree view.JSON to Excel ConverterTurn JSON into a styled .xlsx spreadsheet; nested arrays become their own linked sheets.JSON to CSVConvert JSON data to CSV for spreadsheets.CSV to JSONConvert CSV data to JSON with live preview.Excel to CSVConvert XLSX spreadsheets to CSV.CSV ViewerOpen a CSV or TSV file as a sortable, filterable table.Excel Viewer (XLSX / XLS)Open XLSX, XLS and ODS spreadsheets in your browser without Excel.Line Ending ConverterConvert text and files between CRLF, LF and CR line endings.Markdown to HTMLConvert Markdown to clean HTML with a live editor.XML to JSONConvert XML to JSON with validation.Text Encoding ConverterDetect and convert text file encodings like UTF-8, UTF-16 and Latin-1.JSON ViewerExplore JSON as a collapsible tree, search keys and values and copy any node's path.TTF to WOFF2 ConverterConvert TTF and OTF fonts to WOFF2 or WOFF and get a ready @font-face CSS snippet.Chmod CalculatorConvert Linux file permissions between checkboxes, octal (755) and symbolic (rwxr-xr-x) notation.Morse Code TranslatorTranslate text to Morse code and back, then play it as sound or a blinking light, or save a WAV.HTML Table GeneratorBuild HTML tables in an editable grid with styles, header rows, CSV import and live preview.Hex to Text ConverterConvert hex to text and text to hex with UTF-8 support and space, 0x, \x or comma formats.JSON to XML ConverterConvert JSON to well-formed XML with attributes, arrays and pretty print.JSON to YAML ConverterConvert JSON to clean YAML as you type, with indent, quoting and sort options.YAML to JSON ConverterConvert YAML to pretty or minified JSON, with errors pinned to the exact line.HTML to Markdown ConverterTurn HTML or pasted rich text into clean Markdown with tables and live preview.Markdown Table GeneratorBuild Markdown tables in a grid or paste from Excel/CSV, with alignment and preview.JSON ValidatorCheck JSON with the exact line and column of each error, fix tips and one-click auto-fix.Image to Base64Convert images to Base64 data URIs, CSS backgrounds and HTML img tags in your browser.Base64 to ImagePaste a Base64 string or data URI to preview, identify and download the image.JSON CompareCompare two JSON documents and see every added, removed and changed path.Hex to DecimalConvert hex to decimal instantly with steps and signed mode.Decimal to HexConvert decimal to hex instantly with steps and signed mode.Binary to DecimalConvert binary to decimal instantly with steps and signed mode.Decimal to BinaryConvert decimal to binary instantly with steps and signed mode.Two's Complement CalculatorDecimal to two's complement binary and back for 4-64 bits, with invert-and-add-1 steps.XML to CSV ConverterConvert XML to CSV: detects repeating records, flattens nested data, pick your columns.CSV to XML ConverterConvert CSV to well-formed XML with custom root and row names, escaping and pretty print.TOML to JSON ConverterConvert TOML to JSON and JSON to TOML with a full v1.0 parser and clear error lines.JSON to C# ClassConvert JSON to C# classes or records with System.Text.Json or Newtonsoft attributes.CSV to YAML ConverterConvert CSV rows to a YAML list of mappings with type inference and delimiter detection.Endianness ConverterSwap byte order of 16, 32 and 64-bit hex values and see big- and little-endian integers and floats.Excel to SQL ConverterTurn an Excel sheet into CREATE TABLE and INSERT statements for MySQL, PostgreSQL, SQLite or SQL Server.Excel to VCF ConverterTurn an Excel contact list into a vCard .vcf file for iPhone, Android, Google or Outlook.File to C ArrayConvert any file into a C or C++ byte array header, like xxd -i, with const and PROGMEM options.Image to C ArrayConvert images to monochrome, RGB565 or RGB888 C arrays for OLED, LCD and TFT displays.JSON Merge ToolDeep-merge two or more JSON objects with array concat, replace or union and a conflict rule.JSONL to CSV ConverterConvert JSON Lines / NDJSON to CSV with flattened columns; streams large files locally.PHP Unserialize OnlineDecode PHP serialize() strings to JSON, a tree or print_r, and serialize JSON back to PHP.SQL Dialect ConverterTranslate SQL between MySQL, PostgreSQL, SQLite, SQL Server, Oracle, BigQuery and more.TSV to JSON ConverterTurn tab-separated data pasted from Excel or Sheets into a JSON array or keyed object.XLS to XLSX ConverterConvert old Excel 97-2003 .xls workbooks to modern .xlsx files in your browser, several at once.XML to Excel ConverterTurn repeating XML elements into an .xlsx spreadsheet with attributes and nested data as columns.XSD to XML Sample GeneratorGenerate a sample XML document from an XSD schema, with types, attributes and namespaces.YAML to CSV ConverterTurn a YAML list of objects into CSV with dot-notation columns, custom column order and download.DOCX to Markdown ConverterConvert Word .docx to clean Markdown with headings, lists, tables, links and images in a ZIP.ES6 to ES5 ConverterTranspile modern JavaScript (ES2015+) to ES5 with Babel: targets, module format and loose mode.JavaScript Object to JSONTurn JS object literals and Python dicts into valid JSON: quotes keys, fixes commas and values.JSON Graph VisualizerSee JSON as an interactive node graph with zoom, collapse and search; export PNG or SVG.KML ViewerOpen KML and KMZ files on an interactive map: placemarks, paths, polygons, folders, export.MySQL to PostgreSQL ConverterConvert MySQL dumps and CREATE TABLE statements to PostgreSQL: types, AUTO_INCREMENT, ENUMs, quotes.Text to CSV ConverterTurn space-aligned, fixed-width, pipe or tab separated text into clean CSV with a live preview.VCF File ViewerOpen vCard .vcf files as contact cards with photos, search and duplicate check, export CSV.XML ViewerBrowse XML as a collapsible tree with search, XPath of any node, attributes and big-file support.JSON SorterSort JSON keys A-Z recursively, sort arrays by value or by a key, then pretty-print or minify.JSON to HTML TableConvert a JSON array of objects into clean HTML table code with CSS styles and a live preview.CSV to SQL ConverterConvert CSV to SQL CREATE TABLE and INSERT statements for MySQL, PostgreSQL, SQLite or SQL Server.IPv4 to IPv6 ConverterConvert IPv4 to IPv4-mapped, 6to4 and NAT64 IPv6, extract IPv4 from IPv6, and get int/hex/binary.cURL to Code ConverterConvert curl commands to JavaScript fetch, Axios, Python requests, Node.js, PHP and Go code.Code to ImageTurn code into a beautiful syntax-highlighted PNG with themes, window frame and background.
See all 129 Data & File Format Converters →