4

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

3
  • Do you have the input as a json string? If so you can use serde_json, there is an example on their github if that is what you want. As for the jsonwebkey crate I am not familliar with it Commented Oct 19, 2020 at 7:27
  • "Not in JSON [...] JSONWebkey" that sounds a lot like JSON, why are you saying it's not? serde should be able to deserialise this to a hashmap just fine, or to a struct of the relevant fields. Commented Oct 19, 2020 at 7:29
  • No, JSON Web key generated from crate 'JsonWebKey_Convert' using '.to_jwk()' is returning string only, Please verify Commented Oct 20, 2020 at 6:12

1 Answer 1

2

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(())
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.