0PricingLogin
Learn Rust Coding · Lesson

Working with JSON

serde_json.

The serde_json crate

serde_json is the JSON format implementation for serde. It provides functions to convert between Rust values and JSON text.

  • to_string / from_str for text
  • Value for dynamic JSON

Struct to JSON string

serde_json::to_string serializes any Serialize value to a JSON string.

use serde::Serialize;

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

fn main() {
    let u = User { id: 1, name: "Alice".to_string() };
    let json = serde_json::to_string(&u).unwrap();
    println!("{}", json);
}

All lessons in this course

  1. Serialize and Deserialize
  2. Working with JSON
  3. Custom Serialization
  4. Other Formats
← Back to Learn Rust Coding