How to convert vector of tuples to JSON objects?

Viewed 1940

I am creating a REST API in rocket.rs and have a function that returns a vector of tuples that I need to return to the web frontend. The vector is of the form [(1, "abc"), (2, "mno"), (3, "xyz")].

I need to be send out as a JSON list form [{"score": 1, "text": "abc"}, {"score": 2, "text": "mno"}, {"score": 3, "text": "xyz"}].

How do I do that in Rust? I tested it using serde as

let my_list: Vec<(i32, String)> = vec![
    (1, "abc".to_string()),
    (2, "feg".to_string()),
    (3, "xyz".to_string()),
];
let serialized = serde_json::to_string(&my_list).unwrap();

println!("serialized = {}", serialized);

I would need a way to create the key, value pairs and convert. What is the way to do that?

1 Answers

Why are you using tuples? If your tuple fields have "semantic" names you should consider a struct instead, which should also solve your serialization issue:

#[derive(Clone,PartialEq,Eq,PartialOrd,Ord,Hash,Debug,Serialize,Deserialize)]
struct Entry {
    pub score: i32,
    pub text: String,
}
Related