简体   繁体   中英

BTreeMap terminal display issue in Rust

I have a beautified string which I want to associate to a key and I want to display it from a Hashmap or a BTreeMap in Rust. My string is shown below as follows:-

The `beautified_string` which when printed on terminal using println!("{}", beautified_string) 
    
    {
      "a1": "nWM0MM",
      "b1": "YErSKv",
      "c1": "B",
      "d1": [
        "AIBAC",
        "AH8EA"
      ]
    }

However, when I associate this to a map like this

let m = BTreeMap::new()
m.insert("a", beautified_string)

When I do println:("{?,}", m) I get,

{"a": "{\n  \"a1\": \"nWM0MM\",\n  \"b1\": \"YErSKv\",\n  \"c1\": \"B\",\n  \"d1\": [\n    \"AIBAC\",\n    \"AH8EA\"\n  ]\n}"}

Is it possible to get an output like this from the map?

"a": {
  "a1": "nWM0MM",
  "b1": "YErSKv",
  "c1": "B",
  "d1": [
    "AIBAC",
    "AH8EA"
  ]
}

What I did here, was I converted a BTreeMap to a JSON string using serde_json library, and then I used the from_str function to parse a JSON string and convert it to a Rust value

use serde_json::{to_string, json, Value, from_str};
use std::collections::BTreeMap;


fn main() {
    let mut m = BTreeMap::new();

    let beautified_string = json!({
        "a": {
            "a1": "nWM0MM",
            "b1": "YErSKv",
            "c1": "B",
            "d1": [
                "AIBAC",
                "AH8EA"
            ]
        }
    });

    m.insert(0, beautified_string);

    let json = to_string(&m).unwrap();

    let data: Value = from_str(&json).unwrap();

    println!("{:#}", data);

}

link to Rust Playground = https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c9051c6c84618bab2299c17a824c59d4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM