Parsing JSON in Rust e Serde

Mattepuffo's logo
Parsing JSON in Rust e Serde

Parsing JSON in Rust e Serde

Serde è un framework per la serializzazione / deserializzazione in Rust; ed è lo standard de facto per il parsing del JSON.

Oggi ne vediamo un paio di esempi, anche se ne abbiamo già avuto un assaggio parlando di Actix.

Prima di tutto aggiungete queste dipendenze a Cargo.toml:

[dependencies]
serde = { version = "1.0.106", features = ["derive"] }
serde_json = "1.0.52"

Questo un primo esempio con un solo oggetto:

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

#[derive(Serialize, Deserialize)]
struct Book {
    id: i32,
    title: String,
    author: String,
    price: f32,
}

fn main() {
    get_book().unwrap();
}

fn get_book() -> Result<()> {
    let data = r#"
        {
            "id": 1,
            "title": "Le notti di Salem",
            "author": "Stepehn King",
            "price": 10.9
        }"#;

    let b: Book = serde_json::from_str(data)?;
    println!("ID: {}, Titolo: {}, Autore: {}, Prezzo: {}", b.id, b.title, b.author, b.price);
    Ok(())
}

In pratica abbiamo usato una struct che rappresenta il nostro oggetto.

Qui sotto un esempio un pò più verosimile, in cui abbiamo un array di oggetti:

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

#[derive(Serialize, Deserialize)]
struct Book {
    id: i32,
    title: String,
    author: String,
    price: f32,
}

fn main() {
    get_book().unwrap();
}

fn get_book() -> Result<()> {
    let data = r#"
        [
          {
                "id": 1,
                "title": "Le notti di Salem",
                "author": "Stepehn King",
                "price": 10.9
            },
            {
                "id": 2,
                "title": "Sahara",
                "author": "Clive Cussler",
                "price": 15.8
            }
        ]
        "#;

    let books: Vec<Book> = serde_json::from_str(data)?;
    for b in books.iter() {
        println!("ID: {}, Titolo: {}, Autore: {}, Prezzo: {}", b.id, b.title, b.author, b.price);
    }
    Ok(())
}

Sulla stringa abbiamo usato serde_json, e ne abbiamo fatto il parsing.

Abbiamo usato un vector, e ci abbiamo iterato sopra.

Ovviamente i JSON possono essere molto più complicati, ma come punto di partenza può andare.

Enjoy!


Condividi

Commentami!