diff options
author | Louis Pilfold <louis@lpil.uk> | 2022-01-09 22:32:31 +0000 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2022-01-09 22:32:31 +0000 |
commit | 07d4c5e55453450013a0e398b9cc85e13c27d10d (patch) | |
tree | 79e309880b1620d6525fed29bdc0c1f876f0c262 /src | |
parent | 850d26eaaf1c3de9bed14b249b406b19e3b437a4 (diff) | |
download | gleam_json-07d4c5e55453450013a0e398b9cc85e13c27d10d.tar.gz gleam_json-07d4c5e55453450013a0e398b9cc85e13c27d10d.zip |
decode takes a dynamic decoder
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/json.gleam | 24 |
1 files changed, 20 insertions, 4 deletions
diff --git a/src/gleam/json.gleam b/src/gleam/json.gleam index 7db916d..b94a1d4 100644 --- a/src/gleam/json.gleam +++ b/src/gleam/json.gleam @@ -11,6 +11,7 @@ pub type DecodeError { UnexpectedEndOfInput UnexpectedByte(byte: String, position: Int) UnexpectedSequence(byte: String, position: Int) + UnexpectedFormat(List(dynamic.DecodeError)) } /// Decode a JSON string into dynamically typed data which can be decoded into @@ -19,16 +20,31 @@ pub type DecodeError { /// ## Examples /// /// ```gleam -/// > decode("[1,2,3]") -/// Ok(dynamic.from([1, 2, 3])) +/// > decode("[1,2,3]", dynamic.list(of: dynamic.int)) +/// Ok([1, 2, 3]) /// ``` /// /// ```gleam -/// > decode("[") +/// > decode("[", into: dynamic.list(of: dynamic.int)) /// Error(UnexpectedEndOfInput) /// ``` /// -pub external fn decode(String) -> Result(Dynamic, DecodeError) = +/// ```gleam +/// > decode("1", into: dynamic.string) +/// Error(UnexpectedFormat([dynamic.DecodeError("String", "Int", [])])) +/// ``` +/// +pub fn decode( + from json: String, + using decoder: dynamic.Decoder(t), +) -> Result(t, DecodeError) { + try dynamic_value = decode_to_dynamic(json) + dynamic_value + |> decoder + |> result.map_error(UnexpectedFormat) +} + +external fn decode_to_dynamic(String) -> Result(Dynamic, DecodeError) = "gleam_json_ffi" "decode" /// Convert a JSON value into a string. |