Skip to content
This repository was archived by the owner on Mar 29, 2025. It is now read-only.
/ decode Public archive

The result of this experiment has been merged into the Gleam stdlib

Notifications You must be signed in to change notification settings

lpil/decode

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

55 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

decode

Ergonomic dynamic decoders for Gleam!

Package Version Hex Docs

gleam add decode
import decode/zero as decode
import gleam/dynamic.{type Dynamic}


pub type User {
  User(name: String, email: String, is_admin: Bool)
}

/// Decode data of this shape into a `User` record.
///
/// {
///   "name" -> "Lucy",
///   "email" -> "[email protected]",
///   "is-admin" -> true
/// }
///
pub fn run(data: Dynamic) {
  let decoder = {
    use name <- decode.field("name", decode.string)
    use email <- decode.field("email", decode.string)
    use is_admin <- decode.field("is-admin", decode.bool)
    decode.success(User(name:, email:, is_admin:))
  }

  decode.run(data, decoder)
}

Or, alternatively:

import decode
import gleam/dynamic.{type Dynamic}

pub type User {
  User(name: String, email: String, is_admin: Bool)
}

/// Decode data of this shape into a `User` record.
///
/// {
///   "name" -> "Lucy",
///   "email" -> "[email protected]",
///   "is-admin" -> true
/// }
///
pub fn run(data: Dynamic) {
  let decoder =
    decode.into({
      use name <- decode.parameter
      use email <- decode.parameter
      use is_admin <- decode.parameter
      User(name, email, is_admin)
    })
    |> decode.field("name", decode.string)
    |> decode.field("email", decode.string)
    |> decode.field("is-admin", decode.bool)

  decoder
  |> decode.from(data)
}

For more documentation and examples view https://hexdocs.pm/decode.

About

The result of this experiment has been merged into the Gleam stdlib

Resources

Stars

Watchers

Forks

Packages

No packages published