json-tag

Gleam support for JSON#.

Encode/decode helpers for gleam_json using the JSON# convention.

Install

gleam add json_tag

Usage

Encode:

json_tag.encode(tag: "Circle", fields: [#("radius", json.float(4.0))])
|> json.to_string()
// {"#type":"Circle","radius":4.0}

Decode:

// ... after json.decode to dynamic ...
use #(tag, remaining) <- result.try(json_tag.decode(from: decoded))

case tag {
  "Circle" -> {
    // ... decode fields from remaining ...
  }
  "Rectangle" -> {
    // ... decode fields from remaining ...
  }
  _ -> Error(...)
}

Custom tag names

The tag value is just a string you pass to encode and match on in decode — use any name you want.

API

ExportDescription
encode(tag, fields)Create a JSON object with #type set
decode(from)Extract #type tag and return remaining dynamic
tag_of(from)Extract just the #type value
TagEncoderType signature for encode functions
TagDecoderType signature for decode functions
type_fieldThe "#type" constant
Search Document