Stream: beginners

Topic: ✔ How to parse tag unions from JSON?


view this post on Zulip Anton (Nov 17 2026 at 10:16):

Does this work for you @notramo?

ContentPart : { kind : Str, text : Str }

Body := [
    Empty,
    Content(Str),
    Multipart(List(ContentPart)),
].{
    parser_for = |encoding| {
        Parts : List(ContentPart)
        parse_parts = Parts.parser_for(encoding)

        |state|
            match Json.parse_null(encoding, state) {
                Ok(rest) => Ok({ value: Empty, rest })
                Err(_) =>
                    match Json.parse_str(encoding, state) {
                        Ok(str) => Ok({ value: Content(str.value), rest: str.rest })
                        Err(_) => {
                            parts = parse_parts(state)?
                            Ok({ value: Multipart(parts.value), rest: parts.rest })
                        }
                    }
            }
    }
}

parse_body : Str -> Try(Body, [InvalidJson(Str)])
parse_body = |json| Json.parse(json)

view this post on Zulip notramo (Nov 17 2026 at 13:38):

Yes. Thanks!

view this post on Zulip Notification Bot (Nov 17 2026 at 13:38):

notramo has marked this topic as resolved.


Last updated: Nov 26 2026 at 20:35 UTC