Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Read Simple JSON file into a struct

  • Deserialize
  • read_to_string
{
    "x":1,
    "y":2,
    "f": 4.2,
    "text":"Hello World!"
}

Code

use serde::Deserialize;

#[derive(Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
    f: f64,
    text: String,
}

fn main() {
    let filename = "data.json";
    let content = std::fs::read_to_string(filename).unwrap();

    let data: Point = serde_json::from_str(&content).unwrap();
    println!("data = {:?}", data);
    println!("x+y:  {}", data.x + data.y);
    println!("f:    {}", data.f);
    println!("text: {}", data.text);
    println!();

    // Using the Turbofish syntax
    let other = serde_json::from_str::<Point>(&content).unwrap();
    println!("other = {:?}", other);
}

Output

data = Point { x: 1, y: 2, f: 4.2, text: "Hello World!" }
x+y:  3
f:    4.2
text: Hello World!

other = Point { x: 1, y: 2, f: 4.2, text: "Hello World!" }

Cargo.toml

[package]
name = "json-read-to-struct"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = { version = "1.0.204", features = ["derive"] }
serde_json = "1.0.120"