Parse JSON strings into Gleam types
mainTo convert a JSON string back into a Gleam type, use json.parse.
Parsing works in two steps:
- Define a decoder: Use the
gleam/dynamic/decodemodule from the Gleam standard library to define how fields in the JSON should map to your Gleam type (e.g., usingdecode.field). - Execute parsing: Pass the JSON string and your decoder to
json.parse.
json.parse returns a Result(T, json.DecodeError), where T is your target type.
import myapp.{type Cat, Cat}
import gleam/json
import gleam/dynamic/decode
pub fn cat_from_json(json_string: String) -> Result(Cat, json.DecodeError) {
let cat_decoder = {
use name <- decode.field("name", decode.string)
use lives <- decode.field("lives", decode.int)
use nicknames <- decode.field("nicknames", decode.list(decode.string))
decode.success(Cat(name:, lives:, nicknames:))
}
json.parse(from: json_string, using: cat_decoder)
}