How to deserialize a map of string keys and numbers or string values as a HashMap<String, String> with serde?

I have a single level json where the values are of i32s, f32s, and Strings.
How to deserialize that json to HashMap<String, String>?

{
    "key1": "value1",
    "key2": 0,
    "key3": 6.7
}

How to deserialize it? Is there a way in serde that can help here?

let json: HashMap<String, String>= serde_json::from_str(r#"{"key1": "value1", "key2": 0, "key3": 6.7}"#).unwrap();

Maybe you should define an enum to represent your case, and impl Deserialize for it

I know this. I want a work around

@asmmo It would be helpful if you could specify how the strings in Rust should look like after deserialization. For example, what do you want as a result when deserializing "key4": 0.000. Here is a solution which produces:

[src/main.rs:15] map = {
    "key1": "\"value1\"",
    "key2": "0",
    "key3": "6.7",
    "key4": "0.000",
}

Code on the Playground

You can easily deserialize to HashMap<String, serde_json::Value>.

If you want to convert to string on the fly, then you need the deserialize_with annotation and write your own stringifying deserializer.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.