json 🐑

Work with JSON in Gleam!

Under the hood library uses Thoas, the fastest and most memory efficient pure Erlang JSON encoder/decoder.


Add this package to your Gleam project.

gleam add gleam_json


import myapp.{Cat}
import gleam/list
import gleam/json.{object, string, list, int, null}

pub fn cat_to_json(cat: Cat) -> String {
    #("name", string(cat.name)),
    #("lives", int(cat.lives),
    #("flaws", null()),
    #("nicknames", array(cat.nicknames, of: string)),
  |> json.to_string


JSON is decoded into a Dynamic value which can be decoded using the gleam/dynamic module from the Gleam standard library.

import myapp.{Cat}
import gleam/json
import gleam/dynamic.{field, list, int, string}
import gleam/result

pub fn cat_from_json(json_string: String) -> Result<Cat, json.DecodeError> {
  let cat_decoder = dynamic.decode2(
    field("name", of: string),
    field("lives", of: int),
    field("nicknames", of: list(string)),

  json.decode(from: json_string, using: cat_decoder)