Armani_bologne
Armani_bologne

Reputation: 81

How to convert JSON String to HashMap in Rust?

I am receiving a string like below (Not in JSON or HashMap neither) as kind of key value pair from implicit JSONWebkey crate:

{ "kid":"kid-value",
"kty":"RSA",
"use":"sig",
"n":"n-value",
"e":"e-value" }

Now how can I convert to proper HashMap to extract key and value of "e" and "n"? Or is there a simpler way to extract exact value of "e" and "n"?

Upvotes: 4

Views: 3707

Answers (1)

mcarton
mcarton

Reputation: 30061

The string is JSON, so you should just parse it. By default serde_json ignores all unknown fields, so declaring a struct with only the needed fields is enough:

#[derive(serde::Deserialize)]
struct Values {
    n: String,
    e: String,
}

fn main() -> Result<()> {
    let s = r#"{ "kid":"kid-value",
"kty":"RSA",
"use":"sig",
"n":"n-value",
"e":"e-value" }"#;

    let value = serde_json::from_str::<Values>(s)?;

    println!("{}", value.e);
    println!("{}", value.n);

    Ok(())
}

Upvotes: 2

Related Questions