Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

like image 322
Armani_bologne Avatar asked Oct 24 '25 05:10

Armani_bologne


1 Answers

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(())
}
like image 197
mcarton Avatar answered Oct 26 '25 19:10

mcarton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!