Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

String catch all #1029

Open
eliasposen opened this issue Jun 19, 2023 · 1 comment
Open

String catch all #1029

eliasposen opened this issue Jun 19, 2023 · 1 comment

Comments

@eliasposen
Copy link

Hello! I am working on a project where an api response contains metadata that is pretty inconsistent. I would like to retain this metadata in my struct as a string when doing serde_json::from_str() am often getting Error("invalid type: map, expected a string", ...) given the metadata is sometimes a json itself. E.g.

#[derive(Debug, Deserialize)]
struct MyStruct {
    name: String,
    metadata: String, // this is sometimes a string but may be any valid json
}

fn main() {
    let json = r#"{
        "name": "foobar",
        "metadata": {"foo": "bar", "fizz": 42}
    }"#;

    let my_struct: MyStruct = serde_json::from_str(json).unwrap(); // Errors here
}

Is there a way to tell serde_json to just keep metadata as a string regardless if it is actually a map?

Thanks!

@tbu-
Copy link

tbu- commented Jun 20, 2023

You can use Value or RawValue from the serde_json crate to match any kind of value. You can match on Value and use its string if it's a string or serialize the Value again if it is not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants