I have spent close to an hour on this already, so this is a true case of hitting a wall.
For reasons beyond my control, an internal service I am using hands me a JSON that is in this form
let dirty_string = r#""{\"key1\":\"val1\",\"key2\":\"val2\"}""#;
Now obviously this does not look right. My plan it to take this and use serde_json
to construct the appropriate struct but that does not work.
I have tried various ways to remove the multiple escapes.
I have tried various form of using replace
This
let to_format = dirty_string.replace("\\", r#""#);
gives this
"\"{\"key1\":\"val1\",\"key2\":\"val2\"}\""
basically making the matter worse
This let to_format = dirty_string.replace("\", r#""#);
gives this
""{"key1":"val1","key2":"val2"}""
which looks like almost there, but does not work because when I try to parse it into the struct it fails
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Parsed {
key1: String,
key2: String
}
let to_struct: Parsed = serde_json::from_str(&to_format).unwrap();
dbg!(to_struct);
thread main panicked at called `Result::unwrap()` on an `Err` value: Error("invalid type: string "{", expected struct Parsed", line: 1, column: 3) , src/main.rs:440:62
stack backtrace:
0: rust_begin_unwind
So I will really appreciate help here.
How exactly can I successfully removing this annoying back slashes such that it becomes a valid json string that I can then parse to the struct.