[Python] Dynamically parsing API response into the correct types with msgspec

Discussão em 'Python' iniciado por Stack, Maio 25, 2025.

  1. Stack

    Stack Membro Participativo

    Below is a toy example I am unable to get working. How to properly configure msgspec so it will automatically select the correct types (structs)? I can't change the JSON input as it it something that I don't have any control over. I provided 2 examples how that JSON may look like: image or video

    import json
    import msgspec
    from typing import Union

    class Image(msgspec.Struct):
    format: str

    class Video(msgspec.Struct):
    format: str

    MediaType = Union[Image, Video]

    class Media(msgspec.Struct):
    width: int
    height: int
    mediaType: MediaType

    DECODER = msgspec.json.Decoder(Media)

    image = {"width": 100,
    "height": 200,
    "mediaType": {
    "Image": {
    "format": "jpg"
    }
    }
    }

    video = {"width": 100,
    "height": 200,
    "mediaType": {
    "Video": {
    "format": "mp4"
    }
    }
    }


    image_str = json.dumps(image)
    video_str = json.dumps(video)

    image_str_decoded = DECODER.decode(image_str)
    video_str_decoded = DECODER.decode(video_str)

    print(image_str_decoded)
    print(video_str_decoded)


    What I am trying to achieve:

    image_str_decoded(width=100, height=200, mediaType=Image(format=jpg))
    video_str_decoded(width=100, height=200, mediaType=Video(format=mp4))

    Continue reading...

Compartilhe esta Página