A fork of https://github.com/gleam-lang/json for Glistix
Find a file
Image PgBiel 3f1613c56a bump glistix in flake
gotta remove this manual commit later
2025-03-09 23:39:42 -03:00
.github/workflows update ci workflow 2024-04-26 20:48:57 -03:00
src rename package and update README 2025-03-09 23:08:43 -03:00
test rename package and update README 2025-03-09 23:08:43 -03:00
.gitignore Convert to use Gleam build tool 2021-12-31 16:07:45 +00:00
CHANGELOG.md v1.0.0 2024-01-16 13:05:16 +00:00
default.nix add nix files 2024-04-23 19:58:02 -03:00
flake.lock bump glistix in flake 2025-03-09 23:39:42 -03:00
flake.nix bump glistix in flake 2025-03-09 23:39:42 -03:00
gleam.toml rename package and update README 2025-03-09 23:08:43 -03:00
LICENCE update LICENCE, add NOTICE 2024-04-15 15:50:59 -03:00
manifest.toml use glistix 0.7.0 patches 2025-03-09 23:07:28 -03:00
NOTICE update LICENCE, add NOTICE 2024-04-15 15:50:59 -03:00
README.md rename package and update README 2025-03-09 23:08:43 -03:00
shell.nix add nix files 2024-04-23 19:58:02 -03:00

json 🐑

Mirrors: GitHub | Codeberg

Nix-compatible

Work with JSON in Glistix!

This is a fork of gleam_json which adds support for Glistix's Nix target.

Incompatibilities

Please note that, currently, JSON decoding (the decode function) will crash when receiving invalid JSON input on the Nix target instead of gracefully failing and returning an Error.

This is because it uses builtins.fromJSON which aborts execution on invalid input. A fix for this while retaining efficiency would likely depend on changes to Nix itself.

Installation

You can use this fork by running glistix add gleam_json followed by adding the line below to your Glistix project's gleam.toml file (as of Glistix v0.7.0):

[glistix.preview.patch]
# ... Existing patches ...
# Add this line:
gleam_json = { name = "glistix_json", version = ">= 1.0.0 and < 2.0.0" }

This ensures transitive dependencies on gleam_json will also use the patch.

For the most recent instructions, please see the Glistix handbook.

Encoding

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

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

Decoding

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

Warning

On the Nix target, invalid JSON input will cause a crash instead of returning an Error. Ensure you always provide valid JSON input.

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

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

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