English 中文(简体)
How do I unescaped, string that has been escaped multiple times in Rust?
原标题:
  • 时间:2023-05-30 03:01:06
  •  标签:
  • rust

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.

问题回答

暂无回答




相关问题
Creating an alias for a variable

I have the following code in Rust (which will not compile but illustrates what I am after). For readability purposes, I would like to refer the same string with two different names so that the name of ...

Rust Visual Studio Code code completion not working

I m trying to learn Rust and installed the Rust extension for VSCode. But I m not seeing auto-completions for any syntax. I d like to call .trim() on String but I get no completion for it. I read that ...

热门标签