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

Support adjacently tagged enum but with content name equals to tag #2677

Open
WiSaGaN opened this issue Jan 19, 2024 · 4 comments
Open

Support adjacently tagged enum but with content name equals to tag #2677

WiSaGaN opened this issue Jan 19, 2024 · 4 comments

Comments

@WiSaGaN
Copy link
Contributor

WiSaGaN commented Jan 19, 2024

I have:

{"type":"function","function":{"name":"foo","parameters":"bar"}}
{"type":"search","search":{"keyword":"foo"}}

I want them to be deserialized into

#[derive(Deserialize, Serialize)]                                            
#[serde(tag = "type", content = tag)] // Not supported now
#[serde(rename_all = "snake_case")]
enum Tool {
    Function(Function),
    Search(Search),
}
#[derive(Deserialize, Serialize)]
struct Function {
    name: String,
    parameters: String,
}
#[derive(Deserialize, Serialize)]
struct Search {
    keyword: String,
}

And also these structs serialized into those.

Motivated by OpenAI API: https://platform.openai.com/docs/api-reference/chat/create functions

Currently we can get around using below

#[derive(Deserialize, Serialize)]
#[serde(tag = "type")]
enum Tool {
    Function {
        function: Function,
    },
    Search {
        search: Search,
    },
}

But would be much cleaner and avoid inconsistent data if we have native support.

@alteous
Copy link

alteous commented Feb 3, 2024

I would also like to see this feature. This structure is used in glTF, notably by cameras:

{
    "name": "Finite perspective camera",
    "type": "perspective",
    "perspective": {
        "aspectRatio": 1.5,
        "yfov": 0.660593,
        "zfar": 100,
        "znear": 0.01
    }
}

@andrewtoth
Copy link

From your example it seems like the type field can be skipped for deserialization and then just use the default externally tagged enum representation?

@WiSaGaN
Copy link
Contributor Author

WiSaGaN commented Feb 5, 2024

From your example it seems like the type field can be skipped for deserialization and then just use the default externally tagged enum representation?

Yes, it would work in that case for deserialization, but would be trickier for serialization.

@luminosoda
Copy link

Found this awesome crate https://github.com/de-vri-es/serde-double-tag

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

4 participants