Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert vector into JSON?

I want to use Rust to write a static website but I have a very basic problem to serve data for it. The code is roughly as follows:

pub struct Post {
    title: String,
    created: String,
    link: String,
    description: String,
    content: String,
    author: String,
}

fn main() {
    let mut posts:Vec<Post> = Vec::new();
    let post = Post {
        title: "the title".to_string(),
        created: "2021/06/24".to_string(),
        link: "/2021/06/24/post".to_string(),
        description: "description".to_string(),
        content: "content".to_string(),
        author: "jack".to_string(),
    };
    posts.push(post);
}

How can I convert posts into JSON like:

[{
    "title": "the title",
    "created": "2021/06/24",
    "link": "/2021/06/24/post",
    "description": "description",
    "content": "content",
    "author": "jack",
}]
like image 909
lanqy Avatar asked Sep 04 '26 19:09

lanqy


1 Answers

The simplest and cleanest solution is to use serde's derive abilities to have the JSON structure derived from your Rust struct:

use serde::{Serialize};

#[derive(Serialize)]
pub struct Post {
    title: String,
    created: String,
    link: String,
    description: String,
    content: String,
    author: String,
}

Standard collections automatically implement Serialize when their content does.

You can thus build your json string with

let mut posts:Vec<Post> = Vec::new();
let post = Post {
    title: "the title".to_string(),
    created: "2021/06/24".to_string(),
    link: "/2021/06/24/post".to_string(),
    description: "description".to_string(),
    content: "content".to_string(),
    author: "jack".to_string(),
};
posts.push(post);
let json = serde_json::to_string(&posts)?;

playground

like image 164
Denys Séguret Avatar answered Sep 06 '26 08:09

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!