Home > OS >  How do I change the string element of vector to json in Rust?
How do I change the string element of vector to json in Rust?

Time:05-04

["{\"from\":1,\"date\":1651619967}", 
"{\"from\":1,\"date\":1651619961}"]

I have this type of vector. I want to print out the string elements in this vector in the form of Json.

[{
"from":1,
"date":1651619967
}
, {
"from":1,
"date":1651619967
}]

I want to change it to a beautiful Json form like the one above. How can I do this? The only answer is to use the for statement? I want to know how to do this efficiently.

    let values:Vec<String> = redis_conn
        .zrevrange(room_key, 0, -1)
        .expect("failed to execute ZREVRANGE for 'room_key'");

For your information, the vector above is the result obtained through zrevrange from redis.

CodePudding user response:

The input you have is a rust vec, containing JSON encoded strings, and if I understand the question correctly, you would like to obtain a pretty-printed version of the whole thing (including the containing vec).

One way is to use serde_json to parse the strings, then it's to_string_pretty method to obtain the pretty printed string:

use serde_json::{self, Value};

fn main() {
    let input = vec![
        "{\"from\":1,\"date\":1651619967}", 
        "{\"from\":1,\"date\":1651619961}"
    ];

    // Convert input into Vec<Value>, by parsing each string
    let elems = input.into_iter()
        .map(serde_json::from_str)
        .collect::<Result<Vec<Value>,_>>()
        .unwrap();
    
    let json_val = Value::Array(elems);

    println!("{}", serde_json::to_string_pretty(&json_val).unwrap());
}

Playground

Output:

[
  {
    "date": 1651619967,
    "from": 1
  },
  {
    "date": 1651619961,
    "from": 1
  }
]
  • Related