-2

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"
  ]
}
roku675
  • 59
  • 1
  • 5
  • 1
    You need some deserialization/parsing stuff. This looks like JSON, so... https://docs.rs/serde-json. – Chayim Friedman Dec 14 '22 at 16:24
  • 2
    `Debug` implementations are meant to be an easy way to have a glance at your data. If you need a secific formatting you should create a custom type with a `Display` imlplementation that suits your needs. A newtype struct would work in case you want custom output of an existing datatype. – cafce25 Dec 14 '22 at 17:31

1 Answers1

0

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

chifmaster113
  • 13
  • 1
  • 1