https://github.com/lost22git/dig
Parse path expr as dynamic.Decoder
https://github.com/lost22git/dig
decoder gleam gleam-lang json path-expressions
Last synced: 7 months ago
JSON representation
Parse path expr as dynamic.Decoder
- Host: GitHub
- URL: https://github.com/lost22git/dig
- Owner: lost22git
- License: mit
- Created: 2024-03-24T14:59:03.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2024-04-17T16:33:18.000Z (almost 2 years ago)
- Last Synced: 2025-03-17T13:18:31.325Z (11 months ago)
- Topics: decoder, gleam, gleam-lang, json, path-expressions
- Language: Gleam
- Homepage:
- Size: 26.4 KB
- Stars: 1
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# dig
[](https://hex.pm/packages/dig)
[](https://hexdocs.pm/dig/)
✨ Parse path expression as [dynamic.Decoder](https://hexdocs.pm/gleam_stdlib/gleam/dynamic.html#Decoder)
## Installation
To add this package to your Gleam project:
```sh
gleam add dig
```
## Usage
```gleam
import gleeunit
import gleeunit/should
import dig
import gleam/option.{None, Some}
import gleam/json
import gleam/dynamic
import gleam/string
import gleam/list
import gleam/io
pub fn dig_test() {
let json_str =
"
{
\"foo\": [
{
\"bar\": [
{
\"baz\": \"a\"
},
{
\"baz\": \"b\"
}
]
},
{
\"bar\": [
{
\"baz\": \"c\"
},
{
\"baz\": \"d\"
}
]
}
],
\"haha\": {
\"meme\": 1
}
}
"
{
let assert Ok(dig.DigObject(path, decoder)) =
dig.dig(
"foo[1].bar[1].baz"
|> string.split("."),
)
should.equal(path, ["foo[1]", "bar[1]", "baz"])
let assert Ok(d) =
json_str
|> json.decode(decoder)
d
|> dynamic.string()
|> should.equal(Ok("d"))
}
{
let assert Ok(dig.DigList(path, decoder)) =
dig.dig(
"foo[].bar[].baz"
|> string.split("."),
)
should.equal(path, ["foo[]", "bar[]", "baz"])
let assert Ok(d) =
json_str
|> json.decode(decoder)
d
|> list.map(dynamic.string)
|> should.equal([Ok("a"), Ok("b"), Ok("c"), Ok("d")])
}
{
let assert Ok(dig.DigList(path, decoder)) =
dig.dig(
"foo[].miss_me[1].baz"
|> string.split("."),
)
should.equal(path, ["foo[]", "miss_me[1]", "baz"])
let r =
json_str
|> json.decode(decoder)
case r {
Ok(_) -> should.fail()
Error(errors) -> {
io.debug(errors)
Nil
}
}
}
}
```