DevToolsForYou

JSON Formatter, Minifier, and Validator in Rust — Code Examples

JSON Formatter, Minifier, and Validator in RustUse the online tool →

JSON parsing and serialisation is built into every major language. Here is how to parse a JSON string, format (pretty-print) JSON, and handle common edge cases in each language.

Rust uses serde_json for JSON serialization and deserialization. Define structs with #[derive(Serialize, Deserialize)] for typed parsing.

Rust
// Cargo.toml:
// serde = { version = "1", features = ["derive"] }
// serde_json = "1"
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

#[derive(Serialize, Deserialize, Debug)]
struct User {
    name: String,
    age: u32,
}

fn main() {
    // Parse JSON string → typed struct
    let user: User = serde_json::from_str(r#"{"name":"Alice","age":30}"#).unwrap();
    println!("{}", user.name); // Alice

    // Serialize struct → JSON string
    let json_str = serde_json::to_string(&user).unwrap();
    println!("{}", json_str); // {"name":"Alice","age":30}

    // Pretty-print
    let pretty = serde_json::to_string_pretty(&user).unwrap();
    println!("{}", pretty);

    // Dynamic JSON with the json! macro
    let v = json!({ "name": "Bob", "scores": [95, 87, 91] });
    println!("{}", v["name"]); // Bob

    // Parse to untyped Value (unknown structure)
    let dynamic: Value = serde_json::from_str(r#"{"x":1}"#).unwrap();
    println!("{}", dynamic["x"]); // 1
}
Notes & gotchas
  • Add serde = { features = ["derive"] } to Cargo.toml — the derive macros are not enabled by default.
  • serde_json::Value lets you work with JSON of unknown shape; use typed structs for known schemas.
  • from_str returns a Result — always handle the error; malformed JSON panics if unwrapped blindly.
Try it in your browser

Need to json formatter without writing code? The JSON Formatter, Minifier, and Validator runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open JSON Formatter
JSON Formatter, Minifier, and Validator in other languages