Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/gleam-lang/json
🐑 Work with JSON in Gleam!
https://github.com/gleam-lang/json
gleam json
Last synced: 27 days ago
JSON representation
🐑 Work with JSON in Gleam!
- Host: GitHub
- URL: https://github.com/gleam-lang/json
- Owner: gleam-lang
- License: apache-2.0
- Created: 2021-12-28T15:53:16.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2024-04-08T10:47:59.000Z (8 months ago)
- Last Synced: 2024-04-08T11:48:28.270Z (8 months ago)
- Topics: gleam, json
- Language: Gleam
- Homepage: https://hexdocs.pm/gleam_json/
- Size: 60.5 KB
- Stars: 46
- Watchers: 5
- Forks: 10
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
Awesome Lists containing this project
- awesome-gleam - gleam_json - [📚](https://hexdocs.pm/gleam_json/) - Work with JSON in Gleam (Packages / JSON)
README
# json 🐑
Work with JSON in Gleam!
## Installation
Erlang/OTP 27.0 or higher is required when targeting Erlang.
To use earlier versions of Erlang/OTP use version 1.0.1 of
this package.Add this package to your Gleam project.
```shell
# Erlang version <= OTP26
gleam add gleam_json@1# Erlang version >= OTP27
gleam add gleam_json@2
```## Encoding
```gleam
import myapp.{type 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.```gleam
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)
}
```