0
["{\"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.

1
  • 1
    To be clear, you want to convert from string to (pretty) string, right? Also btw, don't worry too much about efficiency because the serialization/deserialization will be the heavier stuff--any object copying or creation in the code you write will be relatively simple and fast. Commented May 4, 2022 at 0:51

1 Answer 1

2

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
  }
]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! This helped me a lot. I wish you good luck on that day
You're welcome @hyerimchoi! Don't forget to accept the answer by clicking on the tick if it answers your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.